Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java custom function on stream

Say I have something like

something.stream()
         .filter(filterMethod) // Same
         .map(mapMethod)       //
         .map(somethingElse)
         .filter(filterMethod) // Same
         .map(mapMethod)       //
         .filter(otherFilter)
         .filter(filterMethod) // Same
         .map(mapMethod)       // 

Could I create custom function on Stream and convert .filter().map() to one method? Implementing own Stream seems to overkill. It would be nice to have some short lambda function or method like

Stream<T> fooFiterMap(Stream<T> stream){
    return stream.filter(filterMethod).map(mapMethod);
}

and then reduce my something stream into

something.stream()
         .fooFilterMap()     // New
         .map(somethingElse)
         .fooFilterMap()     // New
         .filter(otherFilter)
         .fooFilterMap()     // New
like image 947
Dawid Laszuk Avatar asked Jun 22 '26 11:06

Dawid Laszuk


1 Answers

You can obviously write your own one:

<T> Stream<T> fooFiterMap(Stream<T> stream, Predicate<T> predicate, UnaryOperator<T> function) {
    return stream.filter(predicate).map(function);
}

But the real question is why? It's too verbose? If so, than I'll argue - I like the chaining of filter and map more - bit it's subjective I guess. If you think about multiple objects created, than just think about the fact that these are probably stateless lambdas used on the same call-site, thus a single instance of Predicate and Function.

like image 183
Eugene Avatar answered Jun 26 '26 19:06

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!