Use the Java stream to put the last encountered value into the map

I have some codes 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 values from the list and put them into the map All this is perfect My concern is ordering

For example, if the list has:

a1,b1,a2

How to ensure that the final map contains:

a->a2
b->b1

replace

a->a1
b->b1

The incoming list is ordered, stream() Filter () should keep the order, but I'm in collectors You can't see anything about the input order in the tomap document

In general, is this safe or am I lucky in my test case so far? Will I rely on the JVM and risk future changes?

If I just write a for loop, it's easy to guarantee, but the potential popularity of "fuzziness" worries me

I'm not going to use parallelism for this. I just want to understand the behavior of sequential non parallel flows arriving at the tomap

Solution

The term "recent value" is a bit misleading Because you want to get the last value according to the order of encounter, the answer is that tomap will respect the order of encounter

Its documentation references map Merge to explain the semantics of the merge function, but unfortunately, the document is also a little thin It does not mention the fact that this function is explicitly called using (oldvalue, newvalue); It can only be inferred from the code examples

Tomap's documentation further states:

Therefore, if you do not need to encounter an order, it explicitly points to a different collector Generally, all built-in collectors provided by collectors are unordered only when explicitly stated. This is only the case for the "... Concurrent..." collector and toset() collector

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>