Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a best practice to add context to stream elements?

I'd like to add context to elements of a stream. I know I can map to a List containing the element and the context to add, but it seems kind of bloated (computation / memory overhead) and not flexible enough (types are lost). I know I can do something like this:

public record Tuple<A, B> (A a, B b) {}

And then, for example:

stream // Stream<Foo>
    .map(foo -> new Tuple<>(foo, getContext(foo)); // Stream<Tuple<Foo, FooContext>>

But is there a best practice or maybe even a standard implementation with little overhead?

like image 884
Octribin Avatar asked Oct 29 '25 14:10

Octribin


1 Answers

You don't have to create that Tuple class.

You can use, for example, java.util.AbstractMap.SimpleEntry:

stream.map(foo -> new SimpleEntry<>(foo, getContext(foo)))...

I wouldn't call that a standard implementation, but I always prefer to use a JDK class when one is available.

like image 68
Eran Avatar answered Nov 01 '25 05:11

Eran



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!