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