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.