I have some code as follows:
Map<RiskFactor, RiskFactorChannelData> updateMap =
updates.stream().filter(this::updatedValueIsNotNull). // Remove null updated values
collect(Collectors.toMap(
u -> u.getUpdatedValue().getKey(), // then merge into a map of key->value.
Update::getUpdatedValue,
(a, b) -> b)); // If two values have the same key then take the second value
Specifically I want to take the values from the list and put them into the map. That all works perfectly. My concern though is with ordering.
For example if the list has:
a1, b1, a2
How do I ensure that the final map contains:
a->a2
b->b1
Instead of
a->a1
b->b1
The incoming list is ordered, stream().filter()
should have maintained the order but I can't see anything in the documentation of Collectors.toMap
about ordering of the inputs.
Is this safe in the general case or have I just been lucky on my test cases so far? Am I going to be JVM dependent and at risk of this changing in the future?
This is very simple to guarantee if I just write a for
loop but the "fuzzyness" of potential stream behavior is making me concerned.
I'm not planning to use parallel for this, I'm purely seeking to understand the behavior in the case of a sequential non-parallel stream that reaches to toMap
.