Java HashMap

In this tutorial, we will learn about java.util.HashMap, its methods, use cases of it along with the working examples including user-defined or custom key.

What is a HashMap in Java

HashMap used for mapping the key and value pairs and it is a most efficient in terms of getting values of a given key and can be used for the effective caching.

In Java, HashMap is a class and an implementation of the Map interface and which is efficient implementation due to its constant-time complexity of its basic operations.

It is used to map the key-value pairs and this is based on the implementation of the Hashtable but the only difference is Hashtable is synchronized but HashMap is not synchronized making not a thread-safe implementation in case of multi-threaded environments. If need to make thread-safe implementation then need to synchronize externally unlike Hashtable.

Behaviour of HashMap:

  1. This does not give grantee order of keys.
  2. Allows one null key.
  3. Does not allow duplicate keys, in case of duplicate key later will override the value of key.

HashMap methods:

The following are mostly commonly used HashMap methods.

  1. put(key,value)
  2. contains(key)
  3. remove(key)
  4. keyset()

HashMap put() method :

This method is used to add new key-value pair to the existing map.

Syntax:

HashMap<String,Integer> map = new HashMap<>();
map.put("Apple", 100); 

HashMap contains() method :

This method is used to check the given key is present in the map.

Syntax:

HashMap<String,Integer> map = new HashMap<>();
map.put("Apple", 100);
map.containsKey("Apple");

HashMap remove() method :

This method is used for remove the given key from the map.

Syntax:

HashMap<String,Integer> map = new HashMap<>();
map.put("Apple", 100);
map.remove("Apple");

HashMap keyset() method:

This method used to get the all keys present in the map. From the keys which is returned can be used for iterate to perform any operations individually.

Syntax:

HashMap<String,Integer> map = new HashMap<>();
map.put("Apple", 100);
Set<String> keys = map.keySet();

HashMap example with normal key and value pair:

In this example, we will use string as key and value being mapped is an integer.

CopiedCopy Code
import java.util.HashMap;
import java.util.Set;
public class HashMapExample {
	public static void main(String[] args) {
		HashMap<String,Integer> map = new HashMap<>();
		map.put("Apple", 100);
		map.put("Banana", 10);
		map.put("Orange", 5);
		map.put("Mango", 50);
		//print entire map key-value pairs
		System.out.println(map);
		//get the value of Mango key
		System.out.println(map.get("Mango"));
		//Iterate keys of map
		Set<String> keys = map.keySet();
		for(String key : keys) {
			System.out.println(key +" = "+map.get(key));
		}
		map.remove("Banana");
		//print key-values of map after removal
		System.out.println(map);
	}
}

Output :

{Apple=100, Mango=50, Orange=5, Banana=10}
50
Apple = 100
Mango = 50
Orange = 5
Banana = 10
{Apple=100, Mango=50, Orange=5}

HashMap example with custom key and value pair:

In this example, we will a user-defined (or) custom key and value is an integer while storing key-value pairs in the HashMap.

CopiedCopy Code
import java.util.HashMap;
import java.util.Set;
public class HashMapCustomKey {
	public static void main(String[] args) {
		HashMap<CustomKey,Integer> map = new HashMap<>();
		map.put(new CustomKey("Apple"), 100);
		map.put(new CustomKey("Banana"), 10);
		map.put(new CustomKey("Orange"), 5);
		map.put(new CustomKey("Mango"), 50);
		//print entire map key-value pairs
		System.out.println(map);
		//get the value of Mango key
		System.out.println(map.get(new CustomKey("Mango")));
		//Iterate keys of map
		Set<CustomKey> keys = map.keySet();
		for(CustomKey key : keys) {
			System.out.println(key +" = "+map.get(key));
		}
		map.remove(new CustomKey("Banana"));
		//print key-values of map after removal
		System.out.println(map);
	}
	static class CustomKey {
		String fruitName;
		public CustomKey(String fruitName) {
			super();
			this.fruitName = fruitName;
		}
		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + ((fruitName == null) ? 0 : fruitName.hashCode());
			return result;
		}
		@Override
		public boolean equals(Object obj) {
			CustomKey other = (CustomKey) obj;
			if (fruitName.equals(other.fruitName))
				return true;
			return false;
		}
		@Override
		public String toString() {
			return this.fruitName;
		}
	}
}

Output :

{Apple=100, Mango=50, Banana=10, Orange=5}
50
Apple = 100
Mango = 50
Banana = 10
Orange = 5
{Apple=100, Mango=50, Orange=5}

Conclusion :

In this tutorial, we have covered about HashMap and its methods along with the working examples of which includes the user-defined (or) custom key type.