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

Extract rows that have common values in R dataframe

3  Asked on January 31, 2021 by cirrus

     

Sum rows with same Id based on type and exlude where SUM = 0

1  Asked on January 31, 2021 by daniele-arrighi

   

CASE STATEMENT IN WHERE CLAUSE in QUERY

2  Asked on January 31, 2021 by sujeet-chaurasia

   

x86-16 imul instruction “wrong parameters”?

1  Asked on January 30, 2021 by vbvbvb123

     

Find minimum number of digits required to make a given number

4  Asked on January 30, 2021 by saheel-das

   

How create table variable with join in SQL

2  Asked on January 30, 2021 by andrii-tkachenko

   

Convert Image to Base64String in SELECT query

2  Asked on January 30, 2021 by arthur-rey

     

Getting this error while rendering the page

4  Asked on January 29, 2021 by vijayt

       

Power set code showing segmentation fault

2  Asked on January 29, 2021

 

Give a delay on Entry textchanged event in python and tkinter

2  Asked on January 29, 2021 by rickifernando

   

Ask a Question

Get help from others!

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