Parsing a list out of lists using Java Streams

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!

1 answer

  • answered 2018-01-11 21:11 Schidu Luca

    Just use flatMap :

    products.stream()
            .flatMap(product -> product.getIngredients().stream())
            .distinct()
            .collect(Collectors.toList());