3

I have a list of products. Each product holds another list of ingredients. How can I use Streams in order to get a list of all ingredients from all products?

products.stream()
        .map(Product::getIngredients())
        .filter(i -> !i.isEmpty())
        .distinct()
        .collect(Collectors.toList());

Above the code as far as I got, so far I'm just getting a list with sublists...

What's the right way to do this?

Thanks a lot!

2

1 Answer 1

7

Just use flatMap :

products.stream()
        .flatMap(product -> product.getIngredients().stream())
        .distinct()
        .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

4 Comments

That'd have to be .flatMap(product -> product.getIngredients().stream())
Or .map(Product::getIngredients).flatMap(List::stream).
@SchiduLuca you btw need to explicitly tell OP that distinct requires hashcode/equals overridden... which you don't know if it's an option or not. otherwise plus one
@Eugene It's worth a mention perhaps, but it's not at all relevant to the question or answer.

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.