Java流按内部数组分组

时间:2018-08-02 18:28:47

标签: java java-8 java-stream

我在下面有Class对象的列表:

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

我想使用流对类型进行分组操作。 例如如果我给出如下响应列表 [{"Alaska", ["state", "admin level1"]}, {"New Jersey", ["state", "admin level2"]}] 结果应为:

{"state":["Alaska", "New Jersey"], "admin level1": ["Alaska"], "admin level2": "New Jersey"}

1 个答案:

答案 0 :(得分:4)

map将每个Response中的字符串数组放入SimpleEntry中,将其展平并应用groupingBy作为下游收集器的mapping

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

如果您希望结果按照帖子中显示的顺序显示,则需要将结果转储到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())));