Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group a stream to a map by using a specific key and value?

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?

like image 337
Marsellus Wallace Avatar asked Feb 08 '19 23:02

Marsellus Wallace


People also ask

Can 2 keys have same value in map?

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.

Which method is used to convert the elements of a Stream to a single value?

reduce: The reduce method is used to reduce the elements of a stream to a single value.


1 Answers

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())));
like image 92
Andreas Avatar answered Nov 14 '22 03:11

Andreas