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())
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With