I'm_Pratik
I'm_Pratik

Reputation: 561

Java stream Collectors.groupingBy() with list of String

I have following class :

Class Foo{
  private String cassette;
  private List<String> organs; //["Lung","Liver"]
  //getter setter
}

I'm collecting data into List<Foo> and I want to group them by organ as Map<String,List<Foo>>

So far I have tried following solution:

Map<Object, List<Foo>> collect = fooList
                                   .stream()
                                   .collect(Collectors.groupingBy(x -> x.getOrgan()));

It returns Map<Object, List<Foo>> instead of Map<String,List<Foo>> as follow:

{[Lung, Liver]=[Foo [cassette=1A, organ=[Lung, Liver]]], [Liver]=[Foo [cassette=2A, organ=[Liver]]]}

Also, how can I make a generic method which will return Map<String,List<Foo>> when I pass only key for grouping of Type<T> for Collectors.groupingBy(T) and it will group by a specified key

Upvotes: 1

Views: 1292

Answers (1)

Eran
Eran

Reputation: 393801

You are grouping by a List<String>, not by a String. To group by a String you have to pre-process the Stream to first obtain all the pairs of (String,Foo):

Map<String,List<Foo>> collect = 
    fooList.stream()
           .flatMap(f -> f.getOrgan().stream().map(o -> new SimpleEntry<>(o,f)))
           .collect(Collectors.groupingBy(Map.Entry::getKey,
                                          Collectors.mapping(Map.Entry::getValue,
                                                             Collectors.toList())));

Upvotes: 7

Related Questions