Search code examples
javacollectionsjava-8java-streamcollectors

Streaming a Map with a nested object in Java8


I have an Map of the format

Map<Object1, List<Object2>> dependencies;

. Can someone please suggest what is the concise way to convert this to a Map<Object1, List < Object3 >> using Java Streams ? Failed attempt to do it with streams is listed below.

class Object2 {

List<Object3> subDependencies;

}

//What I was trying to do
Map<Object1, List<Object3>> results = dependencies.entrySet().stream().flatMap
   (entry -> entry.getValue().stream()
   .collect(Collectors.toMap(entry.getKey(), Object2::getsubDependecies));

Solution

  • Try this:

    Map<Object1, List<Object3>> results = 
        dependencies.entrySet()
                    .stream()
                    .collect(toMap(Map.Entry::getKey, 
                                   e -> e.getValue()
                                         .stream()
                                         .map(Object2::getSubDependecies)
                                         .flatMap(List::stream)
                                         .collect(toList())));