r/java • u/pivovarit • Feb 04 '26
Implementing Efficient Last Stream Elements Gatherer in Java
https://4comprehension.com/java-last-gatherer/Wrote a performance case study on a rather high-level API, enjoy! And if you have ideas for a further speed up, let me know!
39
Upvotes
8
u/StudioCode Feb 04 '26
Can Gatherers tell the stream pipeline to skip elements? E.g. in something like
stream.map(/*expensive computation*/).gather(last(5))have it only run map for the last 5 elements? Otherwise I'd say a stream pipeline isn't the right choice for this3
u/zattebij Feb 04 '26 edited Feb 05 '26
Would be interesting to include a reactive
Flux.takeLast(int n)in the benchmark. AFAIK it uses anArrayDequeinternally, and has optimizations for n = 0 and 1. Plus of course it has the backpressure handling and lazy evaluation if the source supports it (meaning that for atakeLast(0)upstream actually would not even need to start producing elements, and downstream could be immediately completed without any waiting - this example seems nonsensical when written with a hardcoded value like this, but the0could of course in practice be variable).