bol*_*ing 1 java lambda java-8 java-stream
我正在尝试Map根据条件逻辑和挣扎修改 a的键。我是 Java 8 流 API 的新手。假设我有一张这样的地图:
Map<String, String> map = new HashMap<>();
map.put("PLACEHOLDER", "some_data1");
map.put("Google", "some_data2");
map.put("Facebook", "some_data3");
map.put("Microsoft", "some_data4");
Run Code Online (Sandbox Code Playgroud)
当我想做的是PLACEHOLDER根据布尔条件找到引用并有条件地将该键更改为其他内容。我觉得它应该是什么样的下方,但这并不甚至编译过程的。
boolean condition = foo();
map = map.entrySet().stream().filter(entry -> "PLACEHOLDER".equals(entry.getKey()))
.map(key -> {
if (condition) {
return "Apple";
} else {
return "Netflix";
}
}).collect(Collectors.toMap(e -> e.getKey(), Map.Entry::getValue));
Run Code Online (Sandbox Code Playgroud)
我发现这个问题让我觉得也许我不能用 Java 8 流 API 来做到这一点。希望有比我更擅长的人知道如何做到这一点。如果你想玩它,Ideone 链接。
您已过滤掉所有不是 的 元素PLACEHOLDER。您需要将该过滤器逻辑添加到您的map操作中:
final Map<String, String> output = input.entrySet().stream()
.map(e -> {
if (!e.getKey().equals("PLACEHOLDER")) {
return e;
}
if (condition) {
return new AbstractMap.SimpleImmutableEntry<>("Apple", e.getValue());
}
return new AbstractMap.SimpleImmutableEntry<>("Netflix", e.getValue());
}).collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
Run Code Online (Sandbox Code Playgroud)
但正如你保证只有单个实例PLACEHOLDER中Map,你可以做
String placeholderData = input.remove("PLACEHOLDER");
if (placeholderData != null) {
input.put(condition ? "Apple" : "Netflix", placeholderData);
}
Run Code Online (Sandbox Code Playgroud)
如果你真的想使用Streams 来做到这一点,你只需要将条件逻辑移至收集阶段,如下所示:
boolean condition = true;
map.entrySet().stream().collect(Collectors.toMap(
entry -> mapKey(entry.getKey(), condition), Map.Entry::getValue
));
Run Code Online (Sandbox Code Playgroud)
在哪里:
private static String mapKey(String key, boolean condition) {
if (!"PLACEHOLDER".equals(key)) {
return key;
}
if (condition) {
return "Apple";
} else {
return "Netflix";
}
}
Run Code Online (Sandbox Code Playgroud)
然而,蜘蛛鲍里斯的答案的第二部分使用Map.removeandMap.put似乎是最好的方法。