Difference between HashMap, LinkedHashMap, and TreeMap in Java

Last updated May 12, 2022

If you would like to store key-value pairs in a Java program, Java collections offer you a variety of options based on your needs. LinkedHashmap, HashMap, and TreeMap are among the alternatives. The key distinctions between these three are in their internal implementation and specific features that make them more essential in certain contexts.

The Differences between HashMap, LinkedHashMap, and TreeMap in Java

Here are various differences between the three based on their implementation, ordering, sorting, and supporting null keys and values.

a) Implementation

Both HashMap and LinkedHashMap implement the Map interface, whereas TreeMap implements the Map, NavigableMap, and SortedMap interfaces. LinkedHashMap is implemented as a double-linked list bucket, HashMap is implemented as a hash table, and TreeMap is implemented as a Red-Black Tree.

b) Ordering and Sorting

HashMaps do not give ordering of element entries; therefore, you cannot assume any order while iterating over the hashmap's values and keys. The LinkedHashMap, on the other hand, keeps track of the order in which the keys are entered into the map and may be used to keep track of the access order. Finally, TreeMaps provides users total flexibility in over-ordering items by allowing them to pass a custom comparator.

c) Null keys and values

HashMaps and the LinkedHashMap support null values as well as key values, while TreeMaps don't support null values since they support natural sorts of elements.

Example

Let's create a HashMap, a LinkedHashMap, and a TreeMap, in this example

 

import java.util.HashMap;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.TreeMap;

public class HashMap_LinkedHashMap_TreeMap {

            public static void main(String[] args) {

                  Map Treemapu = new TreeMap();

                  Treemapu.put("First", "Java");

                  Treemapu.put("Second", "Python");

                  System.out.println("TreeMap values are: \n" + Treemapu);

                  Map Hashimapu = new HashMap();

                  Hashimapu.put("First", "Java");

                  Hashimapu.put("Second", "Python");

                  System.out.println("HashMap Values are: \n" + Hashimapu);

                  Map LinkedHashiMapu = new LinkedHashMap();

                  LinkedHashiMapu.put("First", "Java");

                  LinkedHashiMapu.put("Second", "Python");

                  System.out.println("LinkedHashMap values are: \n" + LinkedHashiMapu);

            }

}

 

Output

{First=Java, Second=Python}

HashMap Values are:

{Second=Python, First=Java}

LinkedHashMap values are:

{First=Java, Second=Python}

 

Keywords: HashMaps, LinkedHashMap, TreeMap

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

129 Views