I have a getHashMap
method that returns HashMap
. I need to populate a ConcurrentHashMap
(in setConcurrentHashMap
) with the HashMap
.
Is there a way to do it?
Sample code:
//getHashMap return a HashMap<String, String>
Map<String, String> myMap = getHashMap();
TestClass.getSingleton().setConcurrentHashMap(ConcurrentHashMap<String, String> concurrentHashMap)
A quick look at the javadoc shows that ConcurrentHashMap
has a copy constructor that takes a Map as a parameter:
Map<String, String> myMap = getHashMap();
ConcurrentMap<String, String> concurrentMap = new ConcurrentHashMap<> (myMap);
You have the Collections#synchronizedXXX
that works fine for these kind of tasks.
In your case, you'll use the Collections#synchronizedMap(Map)
map.
TestClass.getSingleton()
.setConcurrentHashMap(Collections.synchronizedMap(myMap));
ConcurrentHashMap
class provides a constructor to create a ConcurrentHashMap
from a given Map
.
Map<String, String> myMap = getHashMap();
TestClass.getSingleton()
.setConcurrentHashMap(new ConcurrentHashMap<String, String>(myMap));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.