Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Streams Filter Intention of Lazy Evaluation [duplicate]

Is either option 1 or option 2 below correct (e.g. one preferred over the other) or are they equivalent?

Option 1

collectionOfThings.
    stream().
    filter(thing -> thing.condition1() && thing.condition2())

or

Option 2

collectionOfThings
    .stream()
    .filter(thing -> thing.condition1())
    .filter(thing -> thing.condition2())
like image 617
bn. Avatar asked Apr 09 '16 16:04

bn.


1 Answers

To compile, the second one should be

collectionOfThings.
    stream().
    filter(thing -> thing.condition1()).
    filter(thing -> thing.condition2())

They're both equivalent. Sometimes one is more readable than the other.

An alternative way of writing the second one would be to use a method reference:

collectionOfThings
    .stream()
    .filter(Thing::condition1)
    .filter(Thing::condition2)

Also note that the convention is to place the dot at the beginning of the line rather than the end, as you would write a bulleted list.

like image 169
JB Nizet Avatar answered Oct 22 '22 06:10

JB Nizet