Consider a piece of code:
imnport reactor.util.context.Context
public Context addAll (Context ctx, Map.Entry<String, Object> hashMap) {
Context ctxVar = ctx;
for (Map.Entry<String, Object> e : hashMap.entrySet()) {
if (e.getValue() != null) {
ctxVar = ctxVar.put(e.getKey(), e.getValue());
}
}
return ctxVar;
}
reactor.util.context.Context is immutable class. So put merges old context with new added value and returns new
context.
The question is - is there more compact way to "combine" HashMap into immutable object using java 8 streams? (Not for Context class only)
Note: I have read about java stream collect and it seems that does not work because I have to supply initial Context
and combine several contexts after map but recreate entire context for combine operations I think is too much.
You can use reduce:
Context ctxVar = hashMap.entrySet()
.stream()
.filter(e -> e.getValue() != null)
.reduce(ctx,
(c, e) -> c.put(e.getKey(), e.getValue()),
(c1, c2) -> c1.putAll(c2));
It does seem wasteful, though (in the same way your original loop is wasteful), since it creates multiple Context instances when only the last one is needed.
It would make more sense if you write a static method of the Context class (or a constructor) that accepts a Map and only creates a single Context instance for the entries of the Map. However, I now noticed that you didn't write this Context class, so you can't change it.
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