Create only 1 list from a map where map value is list using JAVA 8 Streams

北城余情 提交于 2019-12-03 00:39:09

问题


I have a Map, where the "value" is a List of projects:

Map<User, List<Project>> projectsMap = ...

I want to extract from the map the projects but in only and just 1 List of projects:

I've already seen answers but they don't apply to my case. I don't want this result:

List<List<Project>> theValueOfTheMap;

The result I want is:

List<Project> projects = ... // All the project in the value's map

How can I achieve this using JAVA 8 Streams? Thanks. Leonardo.


回答1:


Thanks @Holger for the answer.

List<Project> projects = projectsMap.values().stream().flatMap(List::stream)
.collect(‌​Collectors.toList())‌​;

Code to avoid NullPointerException in case a Collection in the value map is Null:

projectsMap.values().stream().filter(Objects::nonNull)
.flatMap(List::stream).collect(Collectors.toList());



回答2:


projectsMap.values().stream().reduce((v1, v2) -> Stream.concat(v1.stream(), v2.stream()).collect(Collectors.toList()))



回答3:


Map has a methos to retrieve all the values from it.

You just need to call projectsMap.values().stream().flatMap(List::stream).collect(Collectors.toList()) to make a List os all objects of the map values.

EDIT: forgot to add flatMap, as Holger commented.



来源:https://stackoverflow.com/questions/39639331/create-only-1-list-from-a-map-where-map-value-is-list-using-java-8-streams

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