Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream group by inner array

I have lists of objects of Class below:

class Response {
     public String shortName; 
     public String[] types;
}

I want to do group by operation on types using streams. e.g. If I given a list of Responses like below [{"Alaska", ["state", "admin level1"]}, {"New Jersey", ["state", "admin level2"]}] Result should be map like :

{"state":["Alaska", "New Jersey"], "admin level1": ["Alaska"], "admin level2": "New Jersey"}
like image 443
Sagar Avatar asked Sep 15 '26 06:09

Sagar


1 Answers

map the string array in each Response into a SimpleEntry, flatten that and apply groupingBy with a mapping as the downstream collector.

Map<String, List<String>> resultSet = 
      responses.stream()
               .flatMap(e -> Arrays.stream(e.getTypes()).map(a -> new AbstractMap.SimpleEntry<>(a, e.getShortName())))
               .collect(Collectors.groupingBy(AbstractMap.SimpleEntry::getKey,
                        Collectors.mapping(AbstractMap.SimpleEntry::getValue, 
                                            Collectors.toList())));

if you want the result in the order shown in your post then you'll want to dump the result into a LinkedHashMap:

...
...
.collect(Collectors.groupingBy(AbstractMap.SimpleEntry::getKey,
       LinkedHashMap::new, // a supplier providing a new empty map into which the results will be inserted
       Collectors.mapping(AbstractMap.SimpleEntry::getValue, Collectors.toList())));
like image 176
Ousmane D. Avatar answered Sep 17 '26 19:09

Ousmane D.