4

If I have a List<List<Foo>> I can use flat map to flatten the list. But I have by MyClass which has a List<Foo> and the Foo class has list of bars List<Bar> then I have to do something like this :

myClass.getFoos().stream().map(Foo::getBars).forEach({
    bar -> // some code
});

Is it possible to use flat map in this scenario so I can get list of bars from MyClass in one shot.

2 Answers 2

3

Try this:

myClass.getFoos().stream()
    .map(Foo::getBars)
    .flatMap(List::stream) // flatten the lists
    .forEach(...);

Note the exlcusive use of method references, which I find neater and easier to read than lambdas.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, I didn't know I can do flat map after map.
3
myClass.getFoos()
        .stream() 
        .flatMap(x -> x.getBars().stream())
        .forEach(...)

Comments

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.