Java HashMap Class Methods with Examples

In this article, we will learn the important HashMap class methods with examples.
This article covers all the important HashMap class APIs with examples.

What Will We Learn?

  1. Map interface Overview
  2. HashMap class Overview
  3. Creating a HashMap and Adding key-value pairs to it
  • put(String key, Integer value)
  • putIfAbsent(String key, Integer value)
  1. HashMap API's for accessing keys and modifying their associated value
  • isEmpty()
  • size()
  • containsKey(Object key)
  • containsValue(Object value)
  • get(Object key)
  1. HashMap remove API's with Examples
  • remove(Object key)
  • remove(Object key, Object value)
  1. HashMap demonstration for null keys and null values
  2. How to perform range view operations in Map?
  • keySet()
  • values()
  • entrySet()
  1. Different ways to iterate over Map
  2. How to store multiple values in Map?
  3. Java 8 forEach() method with Map
  4. Synchronizing Access to Java HashMap

1. Map interface Overview

  1. A Map is an object that maps keys to values. Each key and value pair is known as an entry. The map contains only unique keys.
  2. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction. The Java platform contains three general-purpose Map implementations: HashMap, TreeMap, and LinkedHashMap.
In this guide, we will focus on the implementation of HashMap class.

2. HashMap class Overview

Java HashMap class implements the map interface by using a hash table. It inherits the AbstractMap class and implements Map interface.
The important points about Java HashMap class:
  • A HashMap contains values based on the key.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It maintains no order.
  • Java HashMap is not thread-safe. You must explicitly synchronize concurrent modifications to the HashMap.

3. 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.
// Creating a HashMap
Map<String, Integer> numberMapping = new HashMap<>();

// Adding key-value pairs to a HashMap
numberMapping.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);

put(String key, Integer value)

Associates the specified value with the specified key in this map (optional operation).
// Creating a HashMap
Map<String, Integer> numberMapping = new HashMap<>();

// Adding key-value pairs to a HashMap
numberMapping.put("One", 1);
numberMapping.put("Two", 2);
numberMapping.put("Three", 3);

putIfAbsent(String key, Integer value)

If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
// Creating a HashMap
Map<String, Integer> numberMapping = new HashMap<>();
// 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);

4. HashMap API's for accessing keys and modifying their associated value

  • How to check if a HashMap is empty | isEmpty()
  • How to find the size of a HashMap | size()
  • 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()

isEmpty()

Returns true if this map contains no key-value mappings.
Map<String, String> userCityMapping = new HashMap<>();

// Check if a HashMap is empty
System.out.println("is userCityMapping empty? : " + userCityMapping.isEmpty());

size()

Returns the number of key-value mappings in this map. If the map contains more than Integer.MAX_VALUE elements return Integer.MAX_VALUE.
Map<String, String> userCityMapping = new HashMap<>();
userCityMapping.put("John", "New York");
userCityMapping.put("Rajeev", "Bengaluru");
userCityMapping.put("Steve", "London");
// Find the size of a HashMap
System.out.println("We have the city information of " + userCityMapping.size() + " users");

containsKey(Object key)

Returns true if this map contains a mapping for the specified key. More formally, returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null: key.equals(k)). (There can be at most one such mapping.)
Map<String, String> userCityMapping = new HashMap<>();
userCityMapping.put("John", "New York");
userCityMapping.put("Rajeev", "Bengaluru");
userCityMapping.put("Steve", "London");

String userName = "Steve";
// Check if a key exists in the HashMap
if(userCityMapping.containsKey(userName)) {
 // Get the value assigned to a given key in the HashMap
 String city = userCityMapping.get(userName);
 System.out.println(userName + " lives in " + city);
} else {
 System.out.println("City details not found for user " + userName);
}

containsValue(Object value)

Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations of the Map interface.
Map<String, String> userCityMapping = new HashMap<>();
userCityMapping.put("John", "New York");
userCityMapping.put("Rajeev", "Bengaluru");
userCityMapping.put("Steve", "London");

// Check if a value exists in a HashMap
if(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 not user in the userCityMapping who lives in New York");
}

get(Object key)

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
Map<String, String> userCityMapping = new HashMap<>();
userCityMapping.put("John", "New York");
userCityMapping.put("Rajeev", "Bengaluru");
userCityMapping.put("Steve", "London");

System.out.println("Lisa's city : " + userCityMapping.get("Steve"));

5. HashMap remove API's with Examples

  • Remove a key from a HashMap | remove(Object key)
  • Remove a key from a HashMap only if it is associated with a given value | remove(Object key, Object value)

remove(Object key)

Removes the mapping for a key from this map if it is present (optional operation). More formally, if this map contains a mapping from key k to value v such that (key==null ? k==null: key.equals(k)), that mapping is removed. (The map can contain at most one such mapping.)
Map<String, String> husbandWifeMapping = new HashMap<>();
husbandWifeMapping.put("Jack", "Marie");
husbandWifeMapping.put("Chris", "Lisa");
husbandWifeMapping.put("Steve", "Jennifer");

String husband = "Chris";
String wife = husbandWifeMapping.remove(husband);

remove(Object key, Object value)

Removes the entry for the specified key only if it is currently mapped to the specified value.
Map<String, String> husbandWifeMapping = new HashMap<>();
husbandWifeMapping.put("Jack", "Marie");
husbandWifeMapping.put("Chris", "Lisa");
husbandWifeMapping.put("Steve", "Jennifer");

// 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);

6. HashMap demonstration for null keys and null values

// HashMap demonstration for null keys and null values
private static void nullKeyValueDemo() {
 Map<String, String> map = new HashMap<>();
 map.put(null, null);
 map.put(null, null);

 // iterate map using java 8 forEach method
 map.forEach((k, v) -> {
  System.out.println(k);
  System.out.println(v);
 });

 for (Entry<String, String> entry : map.entrySet()) {
  System.out.println(entry.getKey());
  System.out.println(entry.getValue());
 }
}

// HashMap demonstration for duplicate keys
private static void duplicateKeyDemo() {
 Map<String, String> map = new HashMap<>();
 map.put("key1", "value1");
 map.put("key1", "value2");

 // iterate map using java 8 forEach method
 map.forEach((k, v) -> {
  System.out.println(k);
  System.out.println(v);
 });

 for (Entry<String, String> entry : map.entrySet()) {
  System.out.println(entry.getKey());
  System.out.println(entry.getValue());
 }
}

7. How to perform range view operations in Map?

The Collection view methods allow a Map to be viewed as a Collection in these three ways:
  • keySet — the Set of keys contained in the Map.
  • values — The Collection of values contained in the Map. This Collection is not a Set, because multiple keys can map to the same value.
  • entrySet — the Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry, the type of the elements in this Set.
private static void collectionViewsDemo() {

 Map<String, String> map = new HashMap<>();
 map.put("key1", "value1");
 map.put("key2", "value2");
 map.put("key3", "value3");

 // Returns a Set view of the keys contained in this map
 Set<String> keys = map.keySet();

 // Returns a Collection view of the values contained in this map
 Collection<String> values = map.values();

 // Returns a Set view of the mappings contained in this map
 Set<Entry<String, String>> entry = map.entrySet();

 // iterate map using java 8 forEach method
 map.forEach((k, v) -> {
  System.out.println(k);
  System.out.println(v);
 });

 for (Entry<String, String> pair : entry) {
  System.out.println(pair.getKey());
  System.out.println(pair.getValue());
 }
}

8. Different ways to iterate over Map

private static void iterateMap() {

 Map<String, String> map = new HashMap<>();
 map.put("key1", "value1");
 map.put("key2", "value2");
 map.put("key3", "value3");

 // Returns a Set view of the keys contained in this map
 Set<String> keys = map.keySet();
 // Returns a Collection view of the values contained in this map
 Collection<String> values = map.values();
 // Returns a Set view of the mappings contained in this map
 Set<Entry<String, String>> entry = map.entrySet();
 for (Entry<String, String> pair : entry) {
  System.out.println(pair.getKey());
  System.out.println(pair.getValue());
 }

 // iterate map using java 8 forEach method
 map.forEach((k, v) -> {
  System.out.println(k);
  System.out.println(v);
 });

}

9. How to store multiple values in Map?

A multimap is like a Map but it can map each key to multiple values.
Let's create a list of objects and map with the key.
private static void multmapDemo() {
 Map<String, List<String>> multimap = new HashMap<>();
 List<String> multiValueList = new ArrayList<>();
 multiValueList.add("value1");
 multiValueList.add("value2");
 multiValueList.add("value3");
 multimap.put("key1", multiValueList);
}

10. Java 8 forEach() method with Map

The normal way to loop a Map.
public static void forEachWithMap() {

 // Before Java 8, how to loop map
 final Map<Integer, Person> map = new HashMap<>();
 map.put(1, new Person(100, "Ramesh"));
 map.put(2, new Person(100, "Ram"));
 map.put(3, new Person(100, "Prakash"));
 map.put(4, new Person(100, "Amir"));
 map.put(5, new Person(100, "Sharuk"));

 for (final Entry<Integer, Person> entry : map.entrySet()) {
  System.out.println(entry.getKey());
  System.out.println(entry.getValue().getName());
 }
}
In Java 8, you can loop a Map with forEach and lambda expression.
public static void forEachWithMap() {

 // Before Java 8, how to loop map
 final Map<Integer, Person> map = new HashMap<>();
 map.put(1, new Person(100, "Ramesh"));
 map.put(2, new Person(100, "Ram"));
 map.put(3, new Person(100, "Prakash"));
 map.put(4, new Person(100, "Amir"));
 map.put(5, new Person(100, "Sharuk"));

 //  In Java 8, you can loop a Map with forEach + lambda expression.
 map.forEach((k,p) -> {
  System.out.println(k);
  System.out.println(p.getName());
 });
}

11. Synchronizing Access to Java HashMap

HashMap is not synchronized, which means you cannot use it on a multi-threaded Java program without external synchronization. In another word, if you share one instance of HashMap between multiple threads, each is either adding, removing or updating entries then it's possible that HashMap loss its structure and not behave as expected.
  • Use the Collections.synchronizedMap() method to obtain a synchronized view of the HashMap.
  • Write the increment logic inside a synchronized block.
  • We can use a ConcurrentHashMap for thread safety instead of the HashMap obtained via Collections.synchronizedMap() method. The ConcurrentHashMap provides thread-safe operations on the Map.
Map<String, String> currencies = new HashMap<String, String>();
currencies.put("USA", "USD");
currencies.put("England", "GBP");
currencies.put("Canada", "CAD");
currencies.put("HongKong", "HKD");
currencies.put("Australia", "AUD");

// Synchronizing HashMap in Java
currencies = Collections.synchronizedMap(currencies);
// Make sure to synchronize Map while Iterating
// getting key set can be outside synchronized block
Set<String> keySet = currencies.keySet();

synchronized (currencies) {
 Iterator<String> itr = keySet.iterator();
 while (itr.hasNext()) {
  System.out.println(itr.next());
 }
}

Further Learning

Comments