有没有更好的方法来映射 Java 流的映射值?
Is there a better way to map over map values with Java streams?
本质上,更好的写法:
Map<String, String> originalMap = getMapOfValues();
Map<String, String> newMap = originalMap.entrySet()
.stream()
.map(entry ->
Maps.immutableEntry(entry.getKey(), mapValue(entry.getValue()))
).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
(Maps.immutableEntry
是 Guava 的方法)
为什么需要将条目映射到 Maps.immutableEntry()
?您可以跳过该步骤:
Map<String, String> originalMap = getMapOfValues();
Map<String, String> newMap =
originalMap.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,
entry -> mapValue(entry.getValue())));
如果不使用 Streams,您可以执行以下操作:
Map<String, String> originalMap = getMapOfValues();
Map<String, String> newMap = new HashMap<>(originalMap);
newMap.replaceAll((key, value) -> mapValue(value));
本质上,更好的写法:
Map<String, String> originalMap = getMapOfValues();
Map<String, String> newMap = originalMap.entrySet()
.stream()
.map(entry ->
Maps.immutableEntry(entry.getKey(), mapValue(entry.getValue()))
).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
(Maps.immutableEntry
是 Guava 的方法)
为什么需要将条目映射到 Maps.immutableEntry()
?您可以跳过该步骤:
Map<String, String> originalMap = getMapOfValues();
Map<String, String> newMap =
originalMap.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,
entry -> mapValue(entry.getValue())));
如果不使用 Streams,您可以执行以下操作:
Map<String, String> originalMap = getMapOfValues();
Map<String, String> newMap = new HashMap<>(originalMap);
newMap.replaceAll((key, value) -> mapValue(value));