Search code examples
javaperformancejava-stream

Is Java stream filter smart enough to ignore unnecessary items in an ordered stream?


Let's say I have the following:

List<Integer> orderedList = Stream.of(5, 4, 0, 2, 1).sorted().toList();

If I apply a filter such as

List<Integer> filteredList = orderedList.stream().filter(integer -> integer < 3).toList();

Will filter check all items in orderedList, or given that it's ordered, it will stop filtering after it reaches the first false condition, i.e., integer >= 3, or does it always check all items?

If it checks all items, is there a smarter way to filter items in a situation with an ordered list?


Solution

  • In your scenario, since you return a list with all the elements matching the filter, filter() is applied for all the elements in the stream.

    If you want to stop processing when a specific condition is true/false you can use takeWhile() from Java 9:

    orderedList.stream().takeWhile(v -> v < 3).forEach(System.out::println);