-2

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.

lauer
  • 167
  • 10
  • 4
    `projectsMap.values().stream().flatMap(List::stream).collect(Collectors.toList());` – Holger Sep 22 '16 at 12:42
  • 3
    Possible duplicate of [How to convert a Map to List in Java?](http://stackoverflow.com/questions/1026723/how-to-convert-a-map-to-list-in-java) – DimaSan Sep 22 '16 at 12:43
  • @Holger, your answer is what I need. Why did not you answer in the answers section? thanks. – lauer Sep 22 '16 at 14:41
  • I’m quite sure that this is a duplicate of a previous question… – Holger Sep 22 '16 at 14:47
  • @Holger, it is not. I have a Collection as the values in the map. The previous question is converting a simple Map to a list. I can't make `List temp = new ArrayList<>(membersConnections.values()); ` for may case. Previous question has same answer you gave, but how would I know it will work for a Key, Value map where the value is a Collection? I saw the question, did not applied for my case, so I did not had a look in the answers. – lauer Sep 22 '16 at 16:00
  • 1
    I’m not talking about the link, DimaSan has posted. This topic has been covered before, for sure. I just didn’t had the time to search for a best match yet, that’s why I posted the comment, to give you a quick solution. – Holger Sep 22 '16 at 16:17

3 Answers3

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());
lauer
  • 167
  • 10
0
projectsMap.values().stream().reduce((v1, v2) -> Stream.concat(v1.stream(), v2.stream()).collect(Collectors.toList()))
cd1
  • 15,908
  • 12
  • 46
  • 47
-1

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.

djointster
  • 346
  • 3
  • 12