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?
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
3 Asked on January 31, 2021 by cirrus
1 Asked on January 31, 2021 by srinath
1 Asked on January 31, 2021 by himanshu-ranjan
2 Asked on January 31, 2021 by detly
1 Asked on January 31, 2021 by daniele-arrighi
2 Asked on January 31, 2021 by sujeet-chaurasia
1 Asked on January 30, 2021 by vbvbvb123
6 Asked on January 30, 2021 by jkil
2 Asked on January 30, 2021 by danicee
1 Asked on January 30, 2021 by pavlo
4 Asked on January 30, 2021 by saheel-das
2 Asked on January 30, 2021 by andrii-tkachenko
2 Asked on January 30, 2021 by arthur-rey
0 Asked on January 30, 2021 by bharti-jha
1 Asked on January 29, 2021 by vitesze
4 Asked on January 29, 2021 by vijayt
3 Asked on January 29, 2021 by chris-dixon
2 Asked on January 29, 2021 by rickifernando
Get help from others!
Recent Questions
Recent Answers
© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP