3

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!

Ash
  • 672
  • 6
  • 21
SS'
  • 819
  • 1
  • 8
  • 18
  • 2
    Looks ok, but you can always write a simple test case to check your logic – Ivan Jul 12 '18 at 14:50
  • 1
    I’d remove the obsolete brace pair around `a.date().compareTo(b.date())` for the readability’s sake. Besides that, it looks fine. Alternatively, you can use `BinaryOperator.maxBy(Comparator.comparing(x -> x.date()))` or with `YourType::date` instead of `x -> x.date()`. – Holger Jul 12 '18 at 16:24

1 Answers1

6

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.

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63