1

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));
2
  • Are you trying to combine all Object3 in subDependencies values as a single list? Commented Mar 3, 2021 at 19:27
  • @ernest_k yes. I am trying to combine all subdependencies of Object1 to one map where key is Object1 and Value is list of all the subdependencies. Commented Mar 3, 2021 at 19:30

1 Answer 1

1

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())));
Sign up to request clarification or add additional context in comments.

3 Comments

seems like you're missing 2 closing brackets at the end of your statement
@Yoni Right. Thanks.
Thank you @ETO .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.