在Collectors.toMap中如何获取键值

4
Map<String, Map<String, String>> myValues;

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

我是否有办法在doCalculation函数内部获取Key?我知道我可以再次将getActualKey(entry.getKey())作为参数传递给doCalculation,但我只是不想重复相同的函数两次。

1个回答

6
您可以使用派生密钥将您的条目映射到一个新的中间条目,然后将键值对传递给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())));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接