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

后端 未结 3 1487
小鲜肉
小鲜肉 2021-01-29 11:33

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

Map> projectsMap = ...

I want to extract from the map

相关标签:
3条回答
  • 2021-01-29 12:11
    projectsMap.values().stream().reduce((v1, v2) -> Stream.concat(v1.stream(), v2.stream()).collect(Collectors.toList()))
    
    0 讨论(0)
  • 2021-01-29 12:17

    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());
    
    0 讨论(0)
  • 2021-01-29 12:30

    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.

    0 讨论(0)
提交回复
热议问题