Merge all list values together in a map [duplicate]

旧巷老猫 提交于 2019-12-01 14:53:49

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

Use flatMap on the Stream of map entries :

List<String> list = map.entrySet()
                       .stream()
                       .flatMap(e->e.getValue().stream())
                       .collect(Collectors.toList());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!