Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 903
SS' Avatar asked Oct 17 '25 15:10

SS'


1 Answers

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.

like image 159
Ravindra Ranwala Avatar answered Oct 20 '25 04:10

Ravindra Ranwala