Maps – HashMap, LinkedHashMap, and TreeMap

The map interface is not a subtype of the Collection Interface. All the elements in the Map are stored in the form of the <Key, Value > pair. It contains only the unique keys. It behaves differently from rest of the Collection Types.

A Map is usually used when we need to update the records like, add, delete, update and search on the basis of the Key.

Important points about the Map Interface

  • It cannot contain duplicate keys
  • Two interfaces implements Maps in Java , i.e. Map & SortedMap
  • The elements are inserted on the specific implementation

In this section we will be learning about the different kinds of Maps that are available in Java:

  • HashMap
  • LinkedHashMap
  • TreeMap

Let’s deep dive to understand about each of the above mentioned Maps, in more details

HashMap

HashMaps implement the concepts of Maps, that is, storing the values in key and value formats. It implements the Map Interface. The keys are meant to be unique in the HashMap. We can find this class under the java. util package.

HashMap is very useful when we need to perform operations like search, update, etc. on the elements.

Some important point to note, while working with HashMap:

  • It can have multiple null values but only one null key
  • All the elements are stored in the form of <Key, Value> pair
  • It can only have unique keys
  • It is non-synchronized
  • It maintains no order of insertion
  • It also implements Serializable & Clone-able interface

Internal architecture of the HashMap

It is made up of an array of nodes, which contains 4 fields

  • int Hash
  • K key
  • Node next
  • V Value

Following is the way in which each node in an array looks like:

Example-

import java.util.HashMap;
import java.util.Map;

public class Test {

	public static void main(String args[]) {
		HashMap<Integer, String> map = new HashMap<Integer, String>(); // Creating Map
		map.put(1, "Welcome"); // Adding the elements in the Map
		map.put(2, "To");
		map.put(3, "QATechHub");
	
		
		System.out.println("Key Value pair are :");
		for (Map.Entry val : map.entrySet()) {
			System.out.println(val.getKey() + " " + val.getValue());
		}
	}

}

Output-

Key Value pair are :
1 Welcome
2 To
3 QATechHub

The above example demonstrates the use of HashMap, adding the elements to it and fetching the key value pair.

Following are the methods provided for the HashMap in Java:

MethodDescription
void clear()Removes all the mapping i.e., the key value pair from the Map
boolean isEmpty()Checks if the map is empty or not
Object clone()Returns a copy of the HashMap
Set entrySet()Returns the collection view of the mapping present
Set keySet()Returns the set view of the key mapping
V put(Object key, Object value)Allows to add an object
void putAll(Map map)Allows to add all the elements in the Map
V putIfAbsent(K key, V value)Enters the mentioned key and values only if the same is not already present in the Map
V remove(Object key)Removes the value at the specified key
boolean remove(Object key, Object value)Removes the object and the key specified
boolean containsValue(Object value)Checks whether the Map contains certain value or not
boolean containsKey(Object key)Check if a particular key exists in the Map
boolean equals(Object o)Compares the specified object with the Map
V get(Object key)This method returns the object that contains the value associated with the key
boolean isEmpty()Checks if the map is empty or not
V replace(K key, V value)Replaces the value for the specified key
boolean replace(K key, V oldValue, V newValue)Replaces the old value with the new value at the key location
Collection<V> values()It returns a collection view of the values contained in the map
int size()Returns the size of the Map

LinkedHashMap in Java

LinkedHashMap has all the features of the HashMap with an additional advantage of maintaining the order of the elements in which they are inserted. This LinkedHAsMap implements the Map interface and inherits the properties of the HashMap Class.

It inherits HashMap class and implements the Map interface.

Some important point to note, while working with the LinkedHashMap:

  • It can have multiple null values but only one null key
  • All the elements are stored in the form of <Key, Value> pair
  • It can have only the unique keys
  • It is non-synchronized
  • It maintains the order of insertion
  • It also implements Serializable & Clone-able interface
  • We can find this class under the java.util package

Syntax-

LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();

Example-

import java.util.LinkedHashMap;
import java.util.Map;

public class Test {

	public static void main(String args[]) {
		// Creating LinkedHashMap
		LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>(); 
		map.put(1, "Welcome"); // Adding the elements in the LinkedHashMap
		map.put(2, "To");
		map.put(3, "QATechHub");
	
		
		System.out.println("Key Value pair are :");
		for (Map.Entry val : map.entrySet()) {
			System.out.println(val.getKey() + " " + val.getValue());
		}
	}

}

Output-

Key Value pair are :
1 Welcome
2 To
3 QATechHub

The above example is demonstrating the use of the LinkedHashMap, adding the elements to it and fetching the key value pair.

Following are the methods provided for the LinkedHashMap in Java:

MethodDescription
V get(Object key)Returns the object corresponding to the key
void clear()Removes all the mapping i.e., the key value pair from the Map
boolean containsValue(Object value)Checks whether the Map contains a certain value or not
Set<Map.Entry<K,V>> entrySet()Returns a Set view contained in the map
Set<K> keySet()Returns the set view of the key mapping
protected boolean removeEldestEntry(Map.Entry<K,V> eldest)Provides true result on removing the eldest element from the Map
Collection<V> values()Provides the collection view of the values present in the map
boolean isEmpty()Checks if the map is empty or not
Object clone()Returns a copy of the HashMap
V put(Object key, Object value)Allows to add an object
void putAll(Map map)Allows to add all the elements in the Map
int size()Returns the size of the Map

TreeMap in Java

TreeMap is fast as compared to other Maps available, when we talk about the Data retrieval. It implements the Map interface. It provides a convenient way of storing the elements in the <Key, Value> pair in a sorted order, unlike the HashMap.

Some important points to note while working with the TreeMap:

  • It can have multiple null values but only one null key
  • All the elements are stored in the form of <Key, Value> pair
  • It can only have the unique keys
  • It is non-synchronized
  • It stores the element in an ascending order
  • This class can be found under the java. util package

Syntax-

TreeMap<Integer, String> map = new TreeMap<Integer, String>();

Example-

import java.util.Map;
import java.util.TreeMap;

public class Test {

	public static void main(String args[]) {
		// Creating TreeMap
		TreeMap<Integer, String> map = new TreeMap<Integer, String>(); 
		map.put(1, "Welcome"); // Adding the elements in the TreehMap
		map.put(2, "To");
		map.put(3, "QATechHub");
	
		
		System.out.println("Key Value pair are :");
		for (Map.Entry val : map.entrySet()) {
			System.out.println(val.getKey() + " " + val.getValue());
		}
	}

}

Output-

Key Value pair are :
1 Welcome
2 To
3 QATechHub

Following are the methods provided for the TreeMap in Java:

MethodDescription
Map.Entry<K,V> ceilingEntry(K key)Provides the <key, value> pair having either the least, greater or equal to the specified key, or null if there is no such key
K ceilingKey(K key)Provides the least key
void clear()Removes all <key, value> pairs
Object clone()Returns a TreeMap copy
Map.Entry firstEntry()The <key, value> pair with least key is returned
Map.Entry<K,V> higherEntry(K key)Provides the least key strictly greater than the given key
Set keySet()Provides the collection of keys existing in the map
K lowerKey(K key)It returns the greatest key strictly less than the given key, or null if there is no such key
V put(K key, V value)Allows to add all the elements in the Map
void putAll(Map<? extends K,? extends V> map)Allows to enter the mentioned key and values only if the same is not already present in the Map
V replace(K key, V value)Replaces the value at the specified key
boolean containsKey(Object key)Checks if a particular key exists in the Map
boolean containsValue(Object value)Checks if a particular value exists in the Map
K firstKey()Returns the first key in the TreeSet
V get(Object key)Returns the Object that is specified at the key
K lastKey()Returns the last key
V remove(Object key)Removes the <key, value> pair of the specified key from the map
int size()Returns the size of the Map

Differences between HashMap, LinkedHashMap, And TreeMap

BasisHashMapLinkedHashMapTreeMap
When to UseWhen Search is the important requirementWhen the Insertion deletion order mattersWhen need to work with the sorted Data.
InterfaceImplements MapImplements MapImplements Map, SortedMap, NavigableMap
Null KeysIt is allowed to store Null KeysIt is allowed to store Null KeysNot allowed to Store Null Keys
ComplexityO(1)O(1)O(logN)
Tejasvi Nanda

About the Author

Tejasvi Nanda