Obtaining a key in Collectors.toMap

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

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

Is there a way to get the key inside the doCalculation function? I know that I can pass getActualKey(entry.getKey())again as a parameter toCalculation, but I just don't want to repeat the same function twice.

+4
source share
1 answer

You can match your records with a new intermediate record with a derived key, and then pass a pair of values 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())));
+4
source

Source: https://habr.com/ru/post/1684421/


All Articles