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

余生长醉 提交于 2019-12-03 10:50:17

问题


I want to extract a List<E> from a Map<String,List<E>> (E is a random Class) using stream().

I want a simple one-line method using java 8's stream.

What I have tried until now :

HashMap<String,List<E>> map = new HashMap<>();
List<E> list = map.values(); // does not compile
list = map.values().stream().collect(Collectors.toList()); // does not compile

回答1:


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



回答2:


Or use forEach

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

or as Aomine commented use this

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



回答3:


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



回答4:


In addition to other answers:

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

This could also do the trick.




回答5:


Simply use :-

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



回答6:


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)



回答7:


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.



来源:https://stackoverflow.com/questions/54054448/how-to-get-a-liste-from-a-hashmapstring-liste

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