This question already has an answer here:
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.
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());
来源:https://stackoverflow.com/questions/36330705/merge-all-list-values-together-in-a-map