Java HashMap is a hash table based implementation of Java’s Map interface. A Map, as you might know, is a collection of key-value pairs. It maps keys to values.
Following are few key points to note about HashMaps in Java -
A HashMap cannot contain duplicate keys.
Java HashMap allows null values and the null key.
HashMap is an unordered collection. It does not guarantee any specific order of the elements.
Java HashMap is not thread-safe. You must explicitly synchronize concurrent modifications to the HashMap.
Creating a HashMap and Adding key-value pairs to it
The following example shows how to create a HashMap, and add new key-value pairs to it.
importjava.util.HashMap;importjava.util.Map;publicclassCreateHashMapExample {publicstaticvoidmain(String[] args) {// Creating a HashMapMap<String,Integer> numberMapping =newHashMap<>();// Adding key-value pairs to a HashMapnumberMapping.put("One",1);numberMapping.put("Two",2);numberMapping.put("Three",3);// Add a new key-value pair only if the key does not exist in the HashMap, or is mapped to `null`numberMapping.putIfAbsent("Four",4);System.out.println(numberMapping); }}
# Output
{One=1, Four=4, Two=2, Three=3}
Accessing keys and modifying their associated value in a HashMap
How to check if a given key exists in a HashMap | containsKey()
How to check if a given value exists in a HashMap | containsValue()
How to get the value associated with a given key in the HashMap | get()
How to modify the value associated with a given key in the HashMap | put()
importjava.util.HashMap;importjava.util.Map;publicclassAccessKeysFromHashMapExample {publicstaticvoidmain(String[] args) {Map<String,String> userCityMapping =newHashMap<>();// Check if a HashMap is emptySystem.out.println("is userCityMapping empty? : "+userCityMapping.isEmpty());userCityMapping.put("John","New York");userCityMapping.put("Rajeev","Bengaluru");userCityMapping.put("Steve","London");System.out.println("userCityMapping HashMap : "+ userCityMapping);// Find the size of a HashMapSystem.out.println("We have the city information of "+userCityMapping.size() +" users");String userName ="Steve";// Check if a key exists in the HashMapif(userCityMapping.containsKey(userName)) {// Get the value assigned to a given key in the HashMapString city =userCityMapping.get(userName);System.out.println(userName +" lives in "+ city); } else {System.out.println("City details not found for user "+ userName); }// Check if a value exists in a HashMapif(userCityMapping.containsValue("New York")) {System.out.println("There is a user in the userCityMapping who lives in New York"); } else {System.out.println("There is no user in the userCityMapping who lives in New York"); }// Modify the value assigned to an existing keyuserCityMapping.put(userName,"California");System.out.println(userName +" moved to a new city "+userCityMapping.get(userName) +", New userCityMapping : "+ userCityMapping);// The get() method returns `null` if the specified key was not found in the HashMapSystem.out.println("Lisa's city : "+userCityMapping.get("Lisa")); }}
# Output
is userCityMapping empty? : true
userCityMapping HashMap : {Steve=London, John=New York, Rajeev=Bengaluru}
We have the city information of 3 users
Steve lives in London
There is a user in the userCityMapping who lives in New York
Steve moved to a new city California, New userCityMapping : {Steve=California, John=New York, Rajeev=Bengaluru}
Lisa's city : null
importjava.util.HashMap;importjava.util.Map;publicclassRemoveKeysFromHashMapExample {publicstaticvoidmain(String[] args) {Map<String,String> husbandWifeMapping =newHashMap<>();husbandWifeMapping.put("Jack","Marie");husbandWifeMapping.put("Chris","Lisa");husbandWifeMapping.put("Steve","Jennifer");System.out.println("Husband-Wife Mapping : "+ husbandWifeMapping);// Remove a key from the HashMap// Ex - Unfortunately, Chris got divorced. Let's remove him from the mappingString husband ="Chris";String wife =husbandWifeMapping.remove(husband);System.out.println("Couple ("+ husband +" => "+ wife +") got divorced");System.out.println("New Mapping : "+ husbandWifeMapping);// Remove a key from the HashMap only if it is mapped to the given value// Ex - Divorce "Jack" only if He is married to "Linda"boolean isRemoved =husbandWifeMapping.remove("Jack","Linda");System.out.println("Did Jack get removed from the mapping? : "+ isRemoved);// remove() returns null if the mapping was not found for the supplied key wife =husbandWifeMapping.remove("David");if(wife ==null) {System.out.println("Looks like David is not married to anyone"); } else {System.out.println("Removed David and his wife from the mapping"); } }}
# Output
Husband-Wife Mapping : {Steve=Jennifer, Chris=Lisa, Jack=Marie}
Couple (Chris => Lisa) got divorced
New Mapping : {Steve=Jennifer, Jack=Marie}
Did Jack get removed from the mapping? : false
Looks like David is not married to anyone
Obtaining the entrySet, keySet, and values from a HashMap
The Map interface provides methods to retrieve the set of entries (key-value pairs), the set of keys, and the collection of values.
The following example shows how to retrieve them from a HashMap -
# Output
countryISOCode entries : [United States of America=US, Japan=JP, China=CN, India=IN, Russia=RU]
countries : [United States of America, Japan, China, India, Russia]
isoCodes : [US, JP, CN, IN, RU]
Iterating over a HashMap
The following example shows different ways of iterating over a HashMap -
Iterating over a HashMap using Java 8 forEach and lambda expression.
Iterating over the HashMap’s entrySet using iterator().
Iterating over the HashMap’s entrySet using Java 8 forEach and lambda expression.
Iterating over the HashMap’s entrySet using simple for-each loop.
Iterating over the HashMap’s keySet.
importjava.util.HashMap;importjava.util.Iterator;importjava.util.Map;importjava.util.Set;publicclassIterateOverHashMap {publicstaticvoidmain(String[] args) {Map<String,Double> employeeSalary =newHashMap<>();employeeSalary.put("David",76000.00);employeeSalary.put("John",120000.00);employeeSalary.put("Mark",95000.00);employeeSalary.put("Steven",134000.00);System.out.println("=== Iterating over a HashMap using Java 8 forEach and lambda ===");employeeSalary.forEach((employee, salary) -> {System.out.println(employee +" => "+ salary); });System.out.println("\n=== Iterating over the HashMap's entrySet using iterator() ===");Set<Map.Entry<String,Double>> employeeSalaryEntries =employeeSalary.entrySet();Iterator<Map.Entry<String,Double>> employeeSalaryIterator =employeeSalaryEntries.iterator();while (employeeSalaryIterator.hasNext()) {Map.Entry<String,Double> entry =employeeSalaryIterator.next();System.out.println(entry.getKey() +" => "+entry.getValue()); }System.out.println("\n=== Iterating over the HashMap's entrySet using Java 8 forEach and lambda ===");employeeSalary.entrySet().forEach(entry -> {System.out.println(entry.getKey() +" => "+entry.getValue()); });System.out.println("\n=== Iterating over the HashMap's entrySet using simple for-each loop ===");for(Map.Entry<String,Double> entry:employeeSalary.entrySet()) {System.out.println(entry.getKey() +" => "+entry.getValue()); }System.out.println("\n=== Iterating over the HashMap's keySet ===");employeeSalary.keySet().forEach(employee -> {System.out.println(employee +" => "+employeeSalary.get(employee)); }); }}
# Output
=== Iterating over a HashMap using Java 8 forEach and lambda ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0
=== Iterating over the HashMap's entrySet using iterator() ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0
=== Iterating over the HashMap's entrySet using Java 8 forEach and lambda ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0
=== Iterating over the HashMap's entrySet using simple for-each loop ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0
=== Iterating over the HashMap's keySet ===
David => 76000.0
John => 120000.0
Mark => 95000.0
Steven => 134000.0
Java HashMap with User defined objects
Check out the following example to learn how to create and work with a HashMap of user defined objects.