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
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);
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.
来源:https://stackoverflow.com/questions/54054448/how-to-get-a-liste-from-a-hashmapstring-liste