Java HashMap tutorial with examples will help you understand how to use Java HashMap in an easy way. HashMap in Java is a hashtable implementation of the Map interface which provides all the optional Map operations. The HashMap class in Java allows null as a key or a value. However, since the keys cannot be duplicated, there can only be one null key in the HashMap object.
The HashMap class is contained in the java.util package. You have to import the java.util package using the import statement to use the HashMap class in the code.
The HashMap class implements the Map interface and extends the AbstractMap class. The HashMap does not guarantee the order of its elements. That means that the elements may not be returned in the same order in which they were inserted into the map.
The HashMap stores keys and values as objects, so we cannot directly add primitive values in the HashMap object. If required, they need to be converted to respective wrapper classes before putting them into the HashMap object.
The HashMap in Java is not a synchronized implementation, it means if multiple threads are simultaneously modifying the HashMap object, the access must be synchronized externally. The synchronizedMap
method of Collections
class should be used to get the synchronized Map from the HashMap object as given below.
1 |
Map<String, String> hMap = Collections.synchronizedMap( new HashMap<String, String>() ); |
You can also use the existing hashmap object instead of creating a new one to get the synchronized map.
How to create objects of the HashMap class?
The HashMap class in Java provides several constructors to create objects. The below given default constructor creates a new and empty HashMap object.
1 |
HashMap<String,String> hmap = new HashMap<String, String>(); |
The keys and values of this hashmap object will be of type String.
The below given overloaded HashMap constructor will create a new hashmap object from the existing map object like TreeMap or another HashMap.
1 |
public HashMap(Map<? extends K,? extends V> anotherMap) |
The hashmap object created by this constructor will have the same mappings as the specified map.
How to copy TreeMap to HashMap using the HashMap constructor?
The below given example shows how to copy a TreeMap object to HashMap using this constructor.
1 2 3 4 5 6 7 8 9 10 11 |
TreeMap<Integer,String> tmap = new TreeMap<Integer, String>(); tmap.put(3, "Three"); tmap.put(1, "One"); tmap.put(2, "Two"); /* * This will copy all the mappings of the TreeMap to HashMap object */ HashMap<Integer,String> hmap = new HashMap<Integer,String>(tmap); System.out.println(hmap); |
Output
1 |
{1=One, 2=Two, 3=Three} |
How to copy HashMap to another HashMap using the HashMap constructor?
Similar to the example given above, instead of TreeMap, you can also copy a HashMap object to another HashMap object using this constructor.
1 2 3 4 5 6 7 8 9 10 11 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); hmap.put(1, "One"); hmap.put(2, "Two"); hmap.put(3, "Three"); /* * This will copy all the mappings of the HashMap to another HashMap object */ HashMap<Integer,String> hmapCopy = new HashMap<Integer,String>(hmap); System.out.println(hmapCopy); |
Output
1 |
{1=One, 2=Two, 3=Three} |
HashMap Methods
The below given are some of the important methods of the HashMap class in Java.
How to add key value mappings to HashMap using the put, putAll and putIfAbsent methods?
The put
method of the HashMap class adds a key value mapping to the hashmap object.
1 |
public V put(K key, V value) |
If the key does not exist in the hashmap, a new mapping will be added and null is returned. If the key exists in the HashMap, the old value mapped to the given key will be replaced by the new value. In this case, an old value will be returned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); /* * this will add mapping 1=>One, and null is returned * as key 1 does not exist in the map */ System.out.println( hmap.put(1, "One") ); /* * this will also add mapping 2=>Two, and null is returned * as key 2 does not exist in the map */ System.out.println( hmap.put(2, "Two") ); /* * this will replace value "One" with "NewOne" for key 1, It reutrns "One" * as the key 1 was previously mapped to the value "One". */ System.out.println( hmap.put(1, "NewOne") ); System.out.println("HashMap contains: " + hmap); |
Output
1 2 3 4 |
null null One HashMap contains: {1=NewOne, 2=Two} |
The put
method replaces a value for a key if the key already exists in the map. If you want to add mapping if and only if the key does not exist in the map, use the putIfAbsent
method.
1 |
public V putIfAbsent(K key, V value) |
The putIfAbsent
method adds a key-value mapping to the HashMap if the key does not already exist in the map and returns null. If the key already exists in the map, the value associated with the key is returned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); /* * this will add mapping 1=>One, and null is returned * as key 1 does not exist in the map */ System.out.println( hmap.putIfAbsent(1, "One") ); /* * this will also add mapping 2=>Two, and null is returned * as key 2 does not exist in the map */ System.out.println( hmap.putIfAbsent(2, "Two") ); /* * This WILL NOT replace "One" with "NewOne". It returns * "One" as it is the value associated with key 1. */ System.out.println( hmap.putIfAbsent(1, "NewOne") ); System.out.println("HashMap contains: " + hmap); |
Output
1 2 3 4 |
null null One HashMap contains: {1=One, 2=Two} |
Difference between put and putIfAbsent methods: If the key does not exist in the map, both the methods behave the same. If the key exists in the map, the put
method replaces an old value with the new value, while the putIfAbsent
method does not.
How to add all mappings of another Map (HashMap, TreeMap) to HashMap?
The putAll
method of the HashMap class adds all mappings of the specified Map object to this HashMap object.
1 |
public void putAll(Map<? extends K,? extends V> anotherMap) |
If the hashmap object already contains the key, the value will be replaced with the value of the specified map for the given key.
The below given example shows how to copy all mapping from the TreeMap to HashMap (or copy all mappings from the HashMap to another HashMap object).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
TreeMap<Integer,String> tmap = new TreeMap<Integer, String>(); tmap.put(1, "ONE"); tmap.put(2, "TWO"); HashMap<Integer,String> hmap = new HashMap<Integer, String>(); hmap.put(2, "Two"); hmap.put(3, "Three"); /* * To add all mappings from TreeMap to HashMap, use the * putAll method. */ /* * this will copy all mappings of treemap to hashmap * 1=>ONE will be copied from treemap to hashmap * Value of key 2 will be replaced with "TWO" * 3=>Three will remain as is */ hmap.putAll(tmap); System.out.println("HashMap contains: " + hmap); |
Output
1 |
HashMap contains: {1=ONE, 2=TWO, 3=Three} |
How to get a value for a given key from the HashMap object using the get and getOrDefault methods?
The get
method of the HashMap class returns a value associated with the specified key. If the key does not exist in the HashMap, it returns null.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); hmap.put(1, "One"); hmap.put(2, "Two"); hmap.put(3, "Three"); hmap.put(5, null); /* * Use the get method to get the value associated with a key */ //this will return "One" System.out.println( hmap.get(1) ); //this will return null as the key 4 does not exist System.out.println( hmap.get(4) ); //this will also return null as the key 5 is mapped to a null value System.out.println( hmap.get(5) ); |
Output
1 2 3 |
One null null |
As you can see from the output, the returned null value does not necessarily mean that the HashMap does not have the specified key. It may be possible that the given key is associated with a null value in the map.
The getOrDefault
method returns a specified default value if the key does not exist in the map instead of returning null.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); hmap.put(1, "One"); hmap.put(2, "Two"); hmap.put(3, "Three"); hmap.put(5, null); /* * Use the getOrDefault method to get the value associated with * a key, if it exists. If it does not, it returns the * specified default value. */ //this will return "One" System.out.println( hmap.getOrDefault(1, "KeyNotFound") ); //this will return "KeyNotFound" as the key 4 does not exist System.out.println( hmap.getOrDefault(4, "KeyNotFound") ); //this will return null as the key 5 is mapped to null value System.out.println( hmap.getOrDefault(5, "KeyNotFound") ); |
Output
1 2 3 |
One KeyNotFound null |
Difference between get and getOrDefault methods: If the specified key exists in the map, both the methods return a value associated with the specified key. But if the key does not exist in the map, the get
method returns null, while the getOrDefault
method returns the specified default value.
How to get the size of the HashMap (HashMap length) using the size method?
The HashMap size
method returns the number of key value mappings contained in the HashMap object.
1 2 3 4 5 6 |
HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("key1", "value1"); hMap.put("key2", "value2"); System.out.println("HashMap size is: " + hMap.size()); |
Output
1 |
HashMap size is: 2 |
The size
method returns 0 if the HashMap is empty.
How to check if HashMap is empty using the isEmpty method?
The HashMap isEmpty
method returns true if this map object does not contain any key value mappings. It returns false if this map has at least one mapping.
1 2 3 4 5 6 7 8 |
HashMap<String, String> hMap = new HashMap<String, String>(); System.out.println("HashMap is empty: " + hMap.isEmpty()); //add a mapping hMap.put("key1", "value1"); System.out.println("HashMap is empty: " + hMap.isEmpty()); |
Output
1 2 |
HashMap is empty: true HashMap is empty: false |
How to get all the keys of HashMap using the keySet method?
The keySet
method of HashMap class returns a set view of all the keys contained in the HashMap object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("key1", "value1"); hMap.put("key2", "value2"); hMap.put("key3", "value3"); /* * To get all keys stored in the HashMap, use * the keySet method. */ Set<String> setKeys = hMap.keySet(); //iterate all HashMap keys System.out.println("Get all keys of HashMap: "); for(String strKey : setKeys){ System.out.println( strKey ); } |
Output
1 2 3 4 |
Get all keys of HashMap: key1 key2 key3 |
The set returned by the keySet
method is backed by the original HashMap object. So any changes you make to the set will also be reflected in the HashMap object, and vice versa.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("key1", "value1"); hMap.put("key2", "value2"); hMap.put("key3", "value3"); System.out.println("HashMap contains: " + hMap); //get the key set Set<String> setKeys = hMap.keySet(); //remove a key from the key set setKeys.remove("key2"); //the corresponding mapping will also be removed from the HashMap System.out.println("HashMap contains (after removal of key): " + hMap); /* * Similarly, if you change the HashMap, the changes will * be reflected in the key set */ //add a mapping to the HashMap hMap.put("key4", "value4"); System.out.println("Key set contains (after addition): " + setKeys); |
Output
1 2 3 |
HashMap contains: {key1=value1, key2=value2, key3=value3} HashMap contains (after removal of key): {key1=value1, key3=value3} Key set contains (after addition): [key1, key3, key4] |
How to get all values of HashMap using the values method?
The HashMap values
method returns Collection view of the values contained in the map object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("key1", "value1"); hMap.put("key2", "value2"); hMap.put("key3", "value3"); hMap.put("key4", "value2"); System.out.println("HashMap contains: " + hMap); /* * To get all the values from the HashMap, use the * values method. */ Collection<String> values = hMap.values(); //iterate through all values of HashMap System.out.println("Get all values from HashMap :"); for(String strValue : values) System.out.println( strValue ); /* * Any change in values collection will be reflected * in the original HashMap, and vice versa. */ //remove a value from the values collection values.remove("value2"); System.out.println("HashMap contains: " + hMap); |
Output
1 2 3 4 5 6 7 |
HashMap contains: {key1=value1, key2=value2, key3=value3, key4=value2} Get all values from HashMap : value1 value2 value3 value2 HashMap contains: {key1=value1, key3=value3, key4=value2} |
How to get all mappings (entries) of HashMap using the entrySet method?
The entrySet
method of the Java HashMap class returns a set view of entries i.e. key-value pairs contained in this hashmap object. The entry set returned by this method is backed by the original map object, so if you make any changes to the entry set it will reflect in the map, and vice versa.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); hmap.put(1, "One"); hmap.put(2, "Two"); hmap.put(3, "Three"); System.out.println("HashMap contains: " + hmap); /* * To get all the mappings or entries contained in this hashmap, use * the entrySet method. */ Set<Map.Entry<Integer, String>> entries = hmap.entrySet(); System.out.println("HashMap entries: " + hmap); /* * Changes you make to entry set will be reflected in the * map, and vice versa. */ //remove a mapping from map hmap.remove(2); System.out.println("HashMap entries: " + hmap); |
Output
1 2 3 |
HashMap contains: {1=One, 2=Two, 3=Three} HashMap entries: {1=One, 2=Two, 3=Three} HashMap entries: {1=One, 3=Three} |
How to remove a key value mapping from the HashMap using the remove method?
The HashMap remove
method removes a key-value mapping from the map for the specified key.
1 |
public V remove(Object key) |
The remove
method returns the value associated with the key or null if the key does not exist in the map. A null can also be returned if the specified key was mapped to a null value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("key1", "value1"); hMap.put("key2", "value2"); hMap.put("key3", "value3"); hMap.put("key4", null); System.out.println("HashMap contains: " + hMap); /* * To remove a mapping from the HashMap, use * the remove method. */ //this will remove key2=value2 mapping and return value2 System.out.println( hMap.remove("key2") ); //this will return null as they key5 does not exist System.out.println( hMap.remove("key5") ); //this will remove key4=>null and returns null System.out.println( hMap.remove("key4") ); System.out.println("HashMap contains: " + hMap); |
Output
1 2 3 4 5 |
HashMap contains: {key1=value1, key2=value2, key3=value3, key4=null} value2 null null HashMap contains: {key1=value1, key3=value3} |
What if you want to remove a key-value pair, if and only if the specified key is associated with a specific value? Well, there is an overloaded version of the remove
method that accepts key and value arguments.
1 |
public boolean remove(Object key, Object value) |
This method removes the mapping if and only if the given key is associated with the given value as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("key1", "value1"); hMap.put("key2", "value2"); hMap.put("key3", "value3"); System.out.println("HashMap contains: " + hMap); /* * To remove a mapping if and only if the key is mapped * to a given value, use the overloaded remove method. */ /* * this will remove key2=value2 mapping and return true * because keys is mapped to value2 */ System.out.println( hMap.remove("key2", "value2") ); /* * This will not remove mapping of key3, because * key3 is not mapped to value4. Will return false. */ System.out.println( hMap.remove("key3", "value4") ); /* * This will return false as key5 does not exist */ System.out.println( hMap.remove("key5", "anyValue") ); System.out.println("HashMap contains: " + hMap); |
Output
1 2 3 4 5 |
HashMap contains: {key1=value1, key2=value2, key3=value3} true false false HashMap contains: {key1=value1, key3=value3} |
How to remove all the mappings from the HashMap (empty HashMap) using the clear method?
The clear
method of the HashMap class removes all mappings from the HashMap object (i.e. empty hashmap or clear hashmap). The HashMap object becomes empty after this method call.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
HashMap<String, String> hMap = new HashMap<String, String>(); hMap.put("key1", "value1"); hMap.put("key2", "value2"); hMap.put("key3", "value3"); System.out.println("Is HashMap empty?: " + hMap.isEmpty()); /* * To remove all the mappings of the HashMap, use the * clear method */ //hashmap will be empty after this method call hMap.clear(); System.out.println("Is HashMap empty?: " + hMap.isEmpty()); |
Output
1 2 |
Is HashMap empty?: false Is HashMap empty?: true |
How to replace a value for the given key of HashMap using the replace method?
The HashMap replace
method replaces a value mapped to a given key only if it mapped to some value.
1 |
public V replace(K key, V value) |
The old value associated with the specified key will be replaced by the specified new value. This method returns the previously associated value with the key if the key exists. It returns null if the key does not exist in the hashmap or the key was previously associated with the null value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); hmap.put(1, "One"); hmap.put(2, "Two"); hmap.put(3, "Three"); hmap.put(5, null); System.out.println("HashMap contains: " + hmap); /* * To replace a value associated with a key, use * the replace method. */ /* * This will replace value "Two" with "NewTwo" for key 2, * because key 2 exists in the hashmap. It will return "Two" * i.e. old value */ System.out.println( hmap.replace(2, "NewTwo") ); /* * This will not do anything as key 4 does not exist * in the hashmap. Will return null */ System.out.println( hmap.replace(4, "NewFour") ); /* * This will replace null with "NewFive" for key 5 * and return null i.e. previous value associated with the * key 5 */ System.out.println( hmap.replace(5, "NewFive") ); System.out.println("HashMap contains: " + hmap); |
Output
1 2 3 4 5 |
HashMap contains: {1=One, 2=Two, 3=Three, 5=null} Two null null HashMap contains: {1=One, 2=NewTwo, 3=Three, 5=NewFive} |
The above given code replaces a value for the given key if the key is mapped to any value. What if you want to replace the value for a given key if and only if the key is mapped to a specific value? In that case, you need to use an overloaded replace
method.
1 |
public boolean replace(K key, oldValue, newValue) |
This method replaces the value of a given key if and only if the key is mapped to a given value. This method returns true if the key exists and the old value is replaced with a new value. It returns false if the key does not exist in the map or the key is not mapped to the specified value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); hmap.put(1, "One"); hmap.put(2, "Two"); hmap.put(3, "Three"); System.out.println("HashMap contains: " + hmap); /* * To replace a value associated with a key, only if * the key is mapped to a specific value, use the * overloaded replace method. */ /* * This will replace value "Two" with "NewTwo" because * the key 2 is mapped to the value "Two". Will return true. */ System.out.println( hmap.replace(2, "Two", "NewTwo") ); /* * This will not replace "Four" with "NewThree" * as the key 3 is not mapped to the value "Four". * Will return false. */ System.out.println( hmap.replace(3, "Four", "NewThree") ); System.out.println("HashMap contains: " + hmap); |
Output
1 2 3 4 |
HashMap contains: {1=One, 2=Two, 3=Three} true false HashMap contains: {1=One, 2=NewTwo, 3=Three} |
How to check if HashMap contains a key using the containsKey method?
The containsKey
method returns true if this HashMap object contains a mapping for the specified key. It returns false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); hmap.put(1, "One"); hmap.put(2, "Two"); hmap.put(3, "Three"); /* * To check if the hashmap contains a key, use the * containsKey method. */ //this will return true because hashmap contains key 2 System.out.println( hmap.containsKey(2) ); //this will return false because hashmap does not contain key 4 System.out.println( hmap.containsKey(4) ); |
Output
1 2 |
true false |
Note: If the HashMap key is an object of a custom class, the class must override the equals
and hashCode
methods for the containsKey
method to work.
How to check if HashMap contains a value using the containsValue method?
The cotnainsValue
of the HashMap class returns true if the specified value is mapped to one or more keys in the map. It returns false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); hmap.put(1, "One"); hmap.put(2, "Two"); hmap.put(3, "Three"); /* * To check if the hashmap contains a value, use the * containsValue method. */ /* * this will return true because hashmap contains value "Three" * mapped to key 3 */ System.out.println( hmap.containsValue("Two") ); /* * this will return false because hashmap does not contain value "four" * mapped to any key */ System.out.println( hmap.containsValue("Four") ); |
Output
1 2 |
true false |
Note: Just like the containsKey
method, If the specified value is an object of a custom class, the class must override the equals
and hashCode
methods for the containsValue
method to work.
How to Iterate HashMap in Java?
There are several ways to iterate over HashMap in Java.
1. Iterate through keys of HashMap
You can iterate over hashmap keys using the keySet
method and enhanced for loop as given below.
1 2 3 4 5 6 7 8 9 10 11 12 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); hmap.put(1, "One"); hmap.put(2, "Two"); hmap.put(3, "Three"); //get hashmap keys Set<Integer> setKeys = hmap.keySet(); //iterate over hashmap keys using the enhanced for loop System.out.println("Iterate through all keys of HashMap"); for(Integer key : setKeys) System.out.println(key); |
Output
1 2 3 4 |
Iterate through all keys of HashMap 1 2 3 |
2. Iterate through values of HashMap
You can iterate over hashmap values using the values
method and enhanced for loop.
1 2 3 4 5 6 7 8 9 10 11 12 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); hmap.put(1, "One"); hmap.put(2, "Two"); hmap.put(3, "Three"); //get hashmap values Collection<String> values = hmap.values(); //iterate over hashmap values using the enhanced for loop System.out.println("Iterate through all values of HashMap"); for(String value : values) System.out.println(value); |
Output
1 2 3 4 |
Iterate through all values of HashMap One Two Three |
3. Iterate through all mappings of HashMap (key-value pairs or entries)
You can get all the hashmap entries using the entrySet
method and then iterate over the entries using the enhanced for loop as given below.
1 2 3 4 5 6 7 8 9 |
HashMap<Integer,String> hmap = new HashMap<Integer, String>(); hmap.put(1, "One"); hmap.put(2, "Two"); hmap.put(3, "Three"); //get hashmap entries and iterate over them System.out.println("Iterate through all key value pairs of HashMap"); for(Map.Entry<Integer, String> entry : hmap.entrySet()) System.out.println( entry.getKey() + " => " + entry.getValue() ); |
Output
1 2 3 4 |
Iterate through all key value pairs of HashMap 1 => One 2 => Two 3 => Three |
Please refer to the complete how to iterate Java HashMap example to know more.
How to clone HashMap in Java using the clone method?
The clone
method of the HashMap class returns a shallow copy of this map object. The keys and values themselves are not copied, only the references are copied. Refer to below given HashMap clone example to understand it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
class Student{ private int id; private String name; public Student(int id, String name){ this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } //for printing purpose public String toString(){ return "[" + getId() + " => " + getName() + "]"; } } public class Example { public static void main(String[] args) { HashMap<Integer, Student> hMapStudents = new HashMap<Integer, Student>(); //add students object hMapStudents.put(1, new Student(1, "Jack") ); hMapStudents.put(2, new Student(2, "Brian") ); hMapStudents.put(3, new Student(3, "Anna") ); hMapStudents.put(4, new Student(4, "Maria") ); System.out.println("Original HashMap contains: " + hMapStudents); /* * To clone the HashMap, use the clone method. */ HashMap<Integer, Student> hMapStudentsClone = (HashMap<Integer, Student>)hMapStudents.clone(); System.out.println("Cloned HashMap contains: " + hMapStudentsClone); /* * Adding or removing objects from either map object does * not affect the other */ //remove an object from the original hashmap hMapStudents.remove(2); //add an object to cloned hashmap hMapStudentsClone.put(5, new Student(5, "John")); System.out.println("After adding removing mappings: "); System.out.println("Original HashMap contains: " + hMapStudents); System.out.println("Cloned HashMap contains: " + hMapStudentsClone); /* * However, changing any objects added as a key or value * in either of the map objects will be reflected in other * object too. It is because both the maps refer to the same * objects, only references are cloned, not the actual objects. */ //change an object in the original map by changing the student name Student student = hMapStudents.get(1); student.setName("Adam"); System.out.println("After changing an object: "); System.out.println("Original HashMap contains: " + hMapStudents); System.out.println("Cloned HashMap contains: " + hMapStudentsClone); } } |
Output
1 2 3 4 5 6 7 8 |
Original HashMap contains: {1=[1 => Jack], 2=[2 => Brian], 3=[3 => Anna], 4=[4 => Maria]} Cloned HashMap contains: {1=[1 => Jack], 2=[2 => Brian], 3=[3 => Anna], 4=[4 => Maria]} After adding removing mappings: Original HashMap contains: {1=[1 => Jack], 3=[3 => Anna], 4=[4 => Maria]} Cloned HashMap contains: {1=[1 => Jack], 2=[2 => Brian], 3=[3 => Anna], 4=[4 => Maria], 5=[5 => John]} After changing an object: Original HashMap contains: {1=[1 => Adam], 3=[3 => Anna], 4=[4 => Maria]} Cloned HashMap contains: {1=[1 => Adam], 2=[2 => Brian], 3=[3 => Anna], 4=[4 => Maria], 5=[5 => John]} |
The below given HashMap examples will help you HashMap concepts in more detail.
Java HashMap Examples
- How to create HashMap in Java (HashMap constructors)
- How to sort HashMap by keys
- How to sort HashMap by values
- How to iterate through HashMap elements
- Convert HashMap to TreeMap
- How to maintain element insertion order in HashMap
- Covert HashMap to ArrayList or List
- HashMap Size Example (HashMap length)
- How to check If HashMap is empty
- How to print HashMap
- How to clear HashMap (delete all mappings)
- Java HashMap replace example
- How to check if key exists in the HashMap
- How to check if value exists in the HashMap
- How to get HashMap key using value example
- Java HashMap get method example
- Java HashMap put method example
- How to get all keys of HashMap using the keySet method
- How to get first key or value from HashMap example
- Java HashMap forEach for loop example
- How to read text file into HashMap example
- How to convert List to HashMap example
- How to convert String or String array to HashMap
- How to write HashMap to a text file in Java
- How to compare two HashMap objects
References:
Java HashMap Javadoc
Please let me know if you liked the Java HashMap tutorial with examples in the comments section below.