Merge all list values together in a map [duplicate]

蹲街弑〆低调 提交于 2019-12-01 13:39:15

问题


I would like to convert a Map like:

Map<String, List<String>> 

to

List<String> 

where the result list is the merge of all List values.


回答1:


You can just have

List<String> result = map.values().stream().flatMap(List::stream).collect(Collectors.toList());

This retrieves the values of the map with values() then flat maps each list into a Stream formed by its elements and collects the result into a list.

Another alternative, without flat mapping each list, and thus may be more performant, is to collect directly the Stream<List<String>> (returned by values().stream()) by calling addAll on each accumulated result.

List<String> result = map.values().stream().collect(ArrayList::new, List::addAll, List::addAll);



回答2:


Use flatMap on the Stream of map entries :

List<String> list = map.entrySet()
                       .stream()
                       .flatMap(e->e.getValue().stream())
                       .collect(Collectors.toList());


来源:https://stackoverflow.com/questions/36330705/merge-all-list-values-together-in-a-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!