1

I was recently going back through old code changing my foreach loops to streams, and I ran across an if statement like condition && condition. So at first I did

.stream()
.filter(x -> cond && cond)

But then I realised it would look better with two filters, one for each condition.

Which is better convention, and which is more efficient when compiled (if there is any difference at all)?

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
Rogue
  • 636
  • 8
  • 22
  • 2
    If you think it looks better, that's probably the most important thing. Don't underestimate code readability. Any gains here are likely to be minimal, but you could always test it yourself to see. – dcsohl Jun 23 '15 at 18:01
  • Just a guess, but I would imagine that the && version is a little quicker because it only needs to traverse the stream once. I don't have a problem reading this one, either. – Trent Small Jun 23 '15 at 18:02
  • Yes, I think I'll just stick with two filter, since realistically I'm the only one who'll be reading it. – Rogue Jun 23 '15 at 18:03
  • 3
    @TrentSmall whether there is one, two or 30 filters, the stream is only traversed once. – JB Nizet Jun 23 '15 at 18:09
  • @JB Nizet Huh, that's pretty cool! I'll have to try those out. – Trent Small Jun 23 '15 at 18:10
  • 2
    Do what is most readable. The performance considerations are generally far less important than readability, and the incremental cost of an added pipeline stage is usually tiny anyway. – Brian Goetz Jun 23 '15 at 18:42

0 Answers0