user1692342
user1692342

Reputation: 5237

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()))
                     );

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

Upvotes: 4

Views: 1568

Answers (1)

shmosel
shmosel

Reputation: 50756

You can map your entries to a new intermediate entry with your derived key, then pass the value pair to 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())));

Upvotes: 6

Related Questions