java - Find first element by predicate -


i've started playing java 8 lambdas , i'm trying implement of things i'm used in functional languages.

for example, functional languages have kind of find function operates on sequences, or lists returns first element, predicate true. way can see achieve in java 8 is:

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

however seems inefficient me, filter scan whole list, @ least understanding (which wrong). there better way?

no, filter not scan whole stream. it's intermediate operation, returns lazy stream (actually intermediate operations return lazy stream). convince you, can following test:

list<integer> list = arrays.aslist(1, 10, 3, 7, 5); int = 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 filter 10 10 

you see 2 first elements of stream processed.

so can go approach fine.


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -