How to get a List<E> from a HashMap<String,List<E>>

馋奶兔 提交于 2019-12-03 01:18:23

map.values() returns a Collection<List<E>> not a List<E>, if you want the latter then you're required to flatten the nested List<E> into a single List<E> as follows:

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

Or use forEach

 map.forEach((k,v)->list.addAll(v));

or as Aomine commented use this

map.values().forEach(list::addAll);
Ravindra Ranwala

Here's an alternate way to do it with Java-9 and above:

List<E> result = map.values()
                    .stream()
                    .collect(Collectors.flatMapping(List::stream, Collectors.toList()));

In addition to other answers:

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

This could also do the trick.

Simply use :-

map.values().stream().flatMap(List::stream).collect(Collectors.toList());

You can use Collection.stream with flatMap as:

Map<String, List<E>> map = new HashMap<>(); // program to interface
List<E> list = map.values()
                  .stream()
                  .flatMap(Collection::stream)
                  .collect(Collectors.toList());

or use a non-stream version as:

List<E> list = new ArrayList<>();
map.values().forEach(list::addAll)

You can use Collectors2.flatCollect from Eclipse Collections

List<String> list = 
    map.values().stream().collect(Collectors2.flatCollect(l -> l, ArrayList::new));

You can also adapt the Map and use the Eclipse Collections MutableMap API.

List<String> list = 
    Maps.adapt(map).asLazy().flatCollect(l -> l).toList();

The method flatCollect is equivalent to the method flatMap, except flatCollect takes an Iterable instead of a Stream.

Note: I am a committer for Eclipse Collections.

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