In Java, you can create a ConcurrentHashMap
from other maps using the new ConcurrentHashMap(Map m)
constructor.
Here is an example of how to create a ConcurrentHashMap
from a HashMap
:
import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class Main { public static void main(String[] args) { // Create a HashMap Map<String, Integer> hashMap = new HashMap<>(); hashMap.put("Apple", 1); hashMap.put("Banana", 2); hashMap.put("Cherry", 3); // Create a ConcurrentHashMap from the HashMap ConcurrentHashMap<String, Integer> concurrentHashMap = new ConcurrentHashMap<>(hashMap); // Print the ConcurrentHashMap System.out.println(concurrentHashMap); // Output: {Apple=1, Banana=2, Cherry=3} } }ruoSce:www.lautturi.com
In this example, we create a HashMap
and add some key-value pairs to it. We then create a ConcurrentHashMap
from the HashMap
using the new ConcurrentHashMap(Map m)
constructor. This creates a new ConcurrentHashMap
with the same key-value pairs as the HashMap
.
You can also create a ConcurrentHashMap
from other maps, such as a TreeMap
or a LinkedHashMap
. Here is an example:
import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class Main { public static void main(String[] args) { // Create a LinkedHashMap Map<String, Integer> linkedHashMap = new LinkedHashMap<>(); linkedHashMap.put("Apple", 1); linkedHashMap.put("Banana", 2); linkedHashMap.put("Cherry", 3); // Create a ConcurrentHashMap from the LinkedHashMap ConcurrentHashMap<String, Integer> concurrentHashMap = new ConcurrentHashMap<>(linkedHashMap); // Print the ConcurrentHashMap System.out.println(concurrentHashMap); // Output: {Apple=1, Banana=2, Cherry=3} } }
In this example, we create a LinkedHashMap
and add some key-value pairs to it. We then create a ConcurrentHashMap
from the LinkedHashMap
using the new ConcurrentHashMap(Map m)
constructor. This creates a new ConcurrentHashMap
with the same key-value pairs as the LinkedHashMap
.
Note that when you create a ConcurrentHashMap
from another map, the ConcurrentHashMap
will not be thread-safe unless the original map is thread-safe.