Note: this question is not related to java.util.Optional
.
When dealing with streams, I often use logic like this:
Stream<FooBar> stream = myInitialStream();
if (needsFilter1) stream = stream.filter(c -> whatever1());
if (needsFilter2) stream = stream.filter(c -> whatever2());
...
return stream.collect(toList());
What I am trying to achieve is converting the code above to a single-expression using chaining. I find this more readable and straight forward. Until now, the only way I found to achieve that was:
return myInitialStream()
.filter(needsFilter1? c->whatever1() : c->true)
.filter(needsFilter2? c->whatever2() : c->true)
.collect(toList());
Still, this would make unnecessary calls to those trivial c->true
lamdas, which might produce some performance cost when scaling up.
So my question is: is there a better way of producing chained stream expressions that include optional filtering?
UPDATE: Maybe I did not make it clear enough, but the point of my question is finding a single-expression solution. If I have to use multiple statements (to initialize a predicate, for example), I could also use the first code-block of my question which essentially does the same.