How to exit Java stream processing after a required number of results?

Stack Overflow Asked by Mandroid on July 31, 2020

I have following code which uses Stream API to find names of first 3 elements in a collection which have calories more than 300:

List<Dish> dishes = ....
List<String> unhealthyDishes =
                                     .filter(dish -> dish.getCalories() > 300)
                                     .map(dish -> dish.getName())

In traditional iterator based imperative approach, I can keep count of the results and hence exit the iteration loop once I have got required number of elements. But above code seems to go through the entire length of the collection. How can I stop it doing so and stop once I have got 3 elements I need?

One Answer

How do you know it checks the other elements as well? I just set up this small test:

String[] words = {"a", "a", "a", "aa"};
List<Integer> shortWords =
     .filter(word -> {
             System.out.println("checking " + word);
             return word.length() == 1;

And the output was:

checking a
checking a
checking a
[1, 1, 1]

Correct answer by tdranv on July 31, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP