我在下面有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"}
答案 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())));