在 Collectors.toMap 获取密钥

Getting Key in Collectors.toMap

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

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

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

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