Java stream group by inner array

Sagar :

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"}
Ousmane D. :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=93199&siteId=1