I have a Stream<Pair<String, String>> myStream;
and I'd like to aggregate it into a Map<String, Set<String>> result;
I managed to get to the following:
Map<String, Set<Pair<String, String>>> result = myStream
.collect(Collectors.groupingBy(Pair::getKey, Collectors.toSet()));
This fails with "Non-static method cannot be referenced from a static contex":
Map<String, Set<String>> result = myStream
.collect(Collectors.groupingBy(Pair::getKey, Pair::getValue, Collectors.toSet()));
What am I doing wrong?
However, none of the existing Java core Map implementations allow a Map to handle multiple values for a single key. As we can see, if we try to insert two values for the same key, the second value will be stored, while the first one will be dropped.
reduce: The reduce method is used to reduce the elements of a stream to a single value.
Correct code is:
Map<String, Set<String>> result = myStream
.collect(Collectors.groupingBy(Pair::getKey,
Collectors.mapping(Pair::getValue, Collectors.toSet())));
If you use import static
, it is shortened to:
Map<String, Set<String>> result = myStream
.collect(groupingBy(Pair::getKey, mapping(Pair::getValue, toSet())));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With