Creating HashMap from Other Maps in Java
Last Updated :
15 Nov, 2021
Map interface present in java.util package represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore, it behaves a bit differently from the rest of the collection types. A map contains unique keys.
There are three main types of maps in java
- HashMap
- LinkedHashMap
- TreeMap
These interfaces extend the Map interface.
There are various ways to convert one map to another:
- Using iterator/a loop
- Using constructor
- Using putAll() method
Method 1: Using iterator/a loop
Iterate each element of the map (LinkedHashMap in this case) and add each one of them in the new HashMap.
Java
import java.util.*;
public class to_hashmap {
public static void main(String a[])
{
LinkedHashMap<String, String> lhm
= new LinkedHashMap<String, String>();
lhm.put( "Apurva" , "Bhatt" );
lhm.put( "James" , "Bond" );
lhm.put( "Scarlett " , "Johansson" );
System.out.println(lhm);
Map<String, String> gfg = new HashMap<String, String>();
for (Map.Entry<String, String> entry : lhm.entrySet())
gfg.put(entry.getKey(), entry.getValue());
System.out.println(gfg);
}
}
|
Output
{Apurva=Bhatt, James=Bond, Scarlett =Johansson}
{James=Bond, Apurva=Bhatt, Scarlett =Johansson}
Method 2: Using constructor
Pass the given Map (TreeMap in this case) to the HashMap constructor–it will automatically take care of converting the given Map to HashMap.
Java
import java.util.*;
public class to_hashmap {
public static void main(String a[])
{
Map<String, String> tm = new TreeMap<String, String>();
tm.put( "Apurva" , "Bhatt" );
tm.put( "James" , "Bond" );
tm.put( "Scarlett " , "Johansson" );
System.out.println(tm);
Map<String, String> gfg = new HashMap<String, String>(tm);
System.out.println(gfg);
}
}
|
Output
{Apurva=Bhatt, James=Bond, Scarlett =Johansson}
{Apurva=Bhatt, James=Bond, Scarlett =Johansson}
Method 3: Using putAll() method
It is similar to the previous method, rather than passing the given Map to HashMap constructor, pass it to the putAll() method and it will automatically convert it to the HashMap.
Java
import java.util.*;
public class two_hashmap {
public static void main(String a[])
{
Map<String, String> tm = new TreeMap<String, String>();
tm.put( "Apurva" , "Bhatt" );
tm.put( "James" , "Bond" );
tm.put( "Scarlett " , "Johansson" );
System.out.println(tm);
Map<String, String> gfg = new HashMap<String, String>();
gfg.putAll(tm);
System.out.println(gfg);
}
}
|
Output
{Apurva=Bhatt, James=Bond, Scarlett =Johansson}
{Apurva=Bhatt, James=Bond, Scarlett =Johansson}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...