java - 我们可以在 Java 8 中迭代时修改 Map 值吗
问题描述
我有一个Map<Integer,String>
. 我需要能够先过滤掉偶数的键,然后迭代映射值并修改映射值的内容。我尝试运行下面的代码,但值没有改变。java 8中是否可以在迭代a时根据某些条件修改值Map
?
Map<Integer,String> m = new HashMap<>();
m.put(1,"ABC");
m.put(2,"PQR");
m.put(3,"XYZ");
m.put(4,"RST");
Map<Integer,String> m1 = m.entrySet().stream()
.filter(map -> map.getKey().intValue() %2 == 0)
.collect(Collectors.toMap(
map -> map.getKey(),map -> map.getValue()));
Map<Integer,String> m3 = m1.entrySet().stream()
.filter(m2 -> {
if(m2.getValue().equalsIgnoreCase("PQR")){
m2.getValue().replace("PQR","PQR1");
} else if(m2.getValue().equalsIgnoreCase("RST")) {
m2.getValue().replace("RST", "RST1");
}
return true;
}).collect(Collectors.toMap(m2 -> m2.getKey(), m2 -> m2.getValue()));
System.out.println(m3);
我得到的答案是,{2=PQR, 4=RST}
但我的答案应该是{2=PQR1, 4=RST1}
解决方案
问题出在replace
方法上:由于String是不可变的,所以这个方法返回一个新的字符串。但是代码忽略了这个返回值。
为了对您的代码进行最小程度的调整,请m3
像这样创建地图:
Map<Integer,String> m3 = m1.entrySet().stream().map(m2 -> {
if(m2.getValue().equalsIgnoreCase("PQR")){
m2.setValue("PQR1");
}else if(m2.getValue().equalsIgnoreCase("RST")) {
m2.setValue("RST1");
}
return m2;
}).collect(Collectors.toMap(m2 -> m2.getKey(), m2 -> m2.getValue()));
推荐阅读
- android - Textview 文本基线,如结束对齐
- javascript - 如何让整个对象在 react-admin 的 SelctInput 中充当 optionValue?
- python - ImportError:无法导入名称“PY2”
- oracle - 通过 JDBC 使用 Google Apps 脚本建立与 oracle 的连接
- c# - 在 C# 中处理事件时消息框不会显示
- android - Firebase 身份验证不会在签名的 apk 中发送 otp
- python - Python, Youtube-video-downloader-merger 我可以让这个脚本运行得更快吗?
- fancybox-3 - 你如何防止花哨的盒子的关闭按钮自动隐藏?
- .net - 如何显示 NuGet 包依赖项?
- ios - 无法使用 Core Data 和 Swift 在表格视图中正确保存和显示数据