Find first element by predicate Find first element by predicate java java

Find first element by predicate


No, filter does not scan the whole stream. It's an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply do the following test:

List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);int a = list.stream()            .peek(num -> System.out.println("will filter " + num))            .filter(x -> x > 5)            .findFirst()            .get();System.out.println(a);

Which outputs:

will filter 1will filter 1010

You see that only the two first elements of the stream are actually processed.

So you can go with your approach which is perfectly fine.


However this seems inefficient to me, as the filter will scan the whole list

No it won't - it will "break" as soon as the first element satisfying the predicate is found. You can read more about laziness in the stream package javadoc, in particular (emphasis mine):

Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. For example, "find the first String with three consecutive vowels" need not examine all the input strings. Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy.


return dataSource.getParkingLots()                 .stream()                 .filter(parkingLot -> Objects.equals(parkingLot.getId(), id))                 .findFirst()                 .orElse(null);

I had to filter out only one object from a list of objects. So i used this, hope it helps.