patternjavaCritical
Find first element by predicate
Viewed 0 times
elementfindpredicatefirst
Problem
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
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?
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?
Solution
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:
Which outputs:
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.
List 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
10You see that only the two first elements of the stream are actually processed.
So you can go with your approach which is perfectly fine.
Code Snippets
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);will filter 1
will filter 10
10Context
Stack Overflow Q#23696317, score: 952
Revisions (0)
No revisions yet.