Home » Java » Find first element by predicate

Find first element by predicate

Posted by: admin November 2, 2017 Leave a comment

Questions:

I’ve just started playing with Java 8 lambdas and I’m trying to implement some of the things that I’m used to in functional languages.

For example, most functional languages have some kind of find function that operates on sequences, or lists that returns the first element, for which the predicate is true. The only way I can see to achieve this in Java 8 is:

lst.stream()
    .filter(x -> x > 5)
    .findFirst()

However this seems inefficient to me, as the filter will scan the whole list, at least to my understanding (which could be wrong). Is there a better way?

Answers:

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 1
will filter 10
10

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.

Questions:
Answers:

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.

Questions:
Answers:
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.

Questions:
Answers:

Unless your list is really huge (thousands of elements), using streams here is just expensive, and even makes the code harder to understand.

Note: java is NOT a functional language (and jvm isn’t particularily suited for implementing functional languages efficiently).

Much simpler and more efficiant is (on all Iterable’s):

for (MyType walk : lst)
    if (walk > 5) { do_whatever; break; }

Or if you wanna skip the iterator:

for (int x=0; x<list.size(); x++)
    if (list.get(x) > 5 { do_whatever; break; }

Actually, I really wonder why some many people suggest this complex and expensive streams machinery, even for trivial things like getting the first element of an array. (yes: arrays are still supported in Java8).