在 Collectors.toMap 中获取密钥


Map<String, Map<String, String>> myValues;
myValues.entrySet().stream.collect(
Collectors.toMap(entry -> getActualKey(entry.getKey()),
entry -> doCalculation(entry.getValue()))
);

有没有办法让我在doComputing函数中获取密钥?我知道我可以再次将getActualKey(entry.getKey())作为参数传递给doComputing,但我只是不想重复相同的函数两次。

您可以使用派生键将条目映射到新的中间条目,然后将值对传递给doCalculation()

myValues.entrySet()
.stream()
.map(e -> new SimpleEntry<>(getActualKey(e.getKey()), e.getValue()))
.collect(Collectors.toMap(e -> e.getKey(), e -> doCalculation(e.getKey(), e.getValue())));

最新更新