-2

I honestly tried to look at a lot of posts but I am not sure what is the correct way of getting a specific key from a ConcurrentHashMap.

  1. How to get the first key in a ConcurrentHashMap?
  2. How to get the key on first encounter of a certain value?
  3. How to update the value of a specific key?
user1464629
  • 57
  • 1
  • 9

1 Answers1

6

Okay, lets tackle these questions one by one:

1) You cannot. A ConcurrentHashMap has no order. There is no "first" and no "last".

2) A ConcurrentHashMap provides an entrySet which is "weakly consistent", so that if the content of the Map changes during iteration you might see the changes, you might not:

public static <K, V> Optional<K> getKeyForVal(final V val, final Map<K, V> map) {
    return map.entrySet().stream()
            .filter(e -> e.getValue().equals(val))
            .map(Map.Entry::getKey)
            .findFirst();
}

Again, there is no "first" this is just the first one encountered during iteration.

3) This is easy, just add the same key -> value pair again, this will update the value for a particular key.

So the main takeaway here is that a ConcurrentHashMap has no order. The order of iteration over a ConcurrentHashMap is undefined and may even change between different iterations. There is no "first", no "last".

Something like ConcurrentSkipListMap does have an ordering, it's sorted by the order of the keys as defined by a Comparator. So that would have a "first" and a "last" element.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166