6

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())
bn.
  • 7,739
  • 7
  • 39
  • 54
  • The answer for the previous question is incorrect. I'm not a benchmarking expert, but my own tests show that Option1 can perform significantly better. I'll post my test code to the other question, and I would appreciate anyone's review of my findings. – Hank D Apr 09 '16 at 19:59

1 Answers1

8

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255