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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With