Answer the question
In order to leave comments, you need to log in
How to properly modify a list inside a ConcurrentHashMap?
As value in ConcurrentHashMap there is a list - List.
It is necessary to modify - add one more value. Trying to do like this - Map.get(i).add(value) throws a java.lang.UnsupportedOperationException. I understand that this list should be modified in a thread-safe way, but I don’t quite understand how to do it correctly.
Please help.
Answer the question
In order to leave comments, you need to log in
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Function;
public final Map<Integer, List<String>> map = new ConcurrentHashMap<>();
public final Function<Integer, List<String>> mapFun = i -> new CopyOnWriteArrayList<>();
map.computeIfAbsent(1, mapFun).add("a");
map.computeIfAbsent(1, mapFun).add("b");
map.computeIfAbsent(1, mapFun).add("c");
The List interface does not have an add operation.
To replenish the list, it must be ArrayList, LinkedList , Vector. https://en.wikiversity.org/wiki/Java_Collections_O...
https://docs.oracle.com/javase/8/docs/api/java/uti...
Appends the specified element to the end of this list (optional operation) .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question