AnswerBun.com

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 = dishes.stream()
                                     .filter(dish -> dish.getCalories() > 300)
                                     .map(dish -> dish.getName())
                                     .limit(3)
                                     .collect(Collectors.toList());

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 = Arrays.stream(words)
     .filter(word -> {
             System.out.println("checking " + word);
             return word.length() == 1;
             })
     .map(String::length)
     .limit(3)
     .collect(Collectors.toList());
        
System.out.println(shortWords);

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!

Related Questions

Remove item from state

3  Asked on December 5, 2020 by clayton-crockville

 

How to concatenate 3 lists even if there are a list null?

2  Asked on December 5, 2020 by alexz

       

Angular 8: Select first element of ng-content

1  Asked on December 5, 2020 by ijustdev

     

docker-compose volume empty

3  Asked on December 5, 2020 by kerby82

   

Extract value of column from a line (variable)

4  Asked on December 4, 2020 by user4516211

       

Merge Two Files in Weka based on date

1  Asked on December 4, 2020 by spwath

 

Set Session ID Cookie in Nuxt Auth

1  Asked on December 4, 2020 by dominooch

   

Warnings in gcc compiler

1  Asked on December 3, 2020 by hygor-marques

     

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP