6 | 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? |
||||||||
|
12
|
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:
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. |
||||
|
2
|
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):
|