SS'
SS'

Reputation: 857

Merge function in ConcurrentHashMap

Got a question about the merge function with ConcurrentHashMaps. New to functional programming so not sure if I'm utilizing it correctly.

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#merge-K-V-java.util.function.BiFunction-

map.merge(consumer, val, (a, b) -> (a.date().compareTo(b.date())) >= 0 ? a : b);

What it should do if I've reasoned it out correctly is insert (consumer, val) into the table if there is no existing entry. If there is, then it should compare the dates of a and b (value in table and my val). If "val" is > than the entry in the table, it should replace it with that. Otherwise, stick with existing entry.

Appreciate any help. Thanks!

Upvotes: 4

Views: 4449

Answers (1)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

Here's one example,

Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");

map.merge(1, "newOne", (v1, v2) -> v1 + ", " + v2);

The third remapping function is used when there's a key conflict. Here's an excerpt from the documentation:

If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. This method may be of use when combining multiple mapped values for a key.

Upvotes: 7

Related Questions