P
P
prizrak392018-11-12 21:10:30
Java
prizrak39, 2018-11-12 21:10:30

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

2 answer(s)
E
Evhen, 2018-11-13
@prizrak39

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");

A
alfss, 2018-11-13
@alfss

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 question

Ask a Question

731 491 924 answers to any question