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?