Differences between TreeMap, HashMap and LinkedHashMap in Java

Java 8Object Oriented ProgrammingProgramming

Details about TreeMap, HashMap and LinkedHashMap that help to differentiate them are given as follows −

TreeMap in Java

A TreeMap in Java is implemented using a Red-Black trees. It has key-value pairs i.e. keys that are associated with the values and the keys are ordered. A TreeMap can only have unique elements and cannot have a null key but have null elements.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.*;
import java.lang.*;
import java.io.*;
public class Demo {
   public static void main (String[] args) {
      TreeMap<Integer, String> tMap = new TreeMap<Integer, String>();
      int[] arr = {1, 3, 5, 7, 9};
      for (int i : arr) {
         tMap.put(i, Integer.toString(i));
      }
      for (int j: tMap.keySet()) {
         System.out.print(j + " ");
      }
   }
}

The output of the above program is as follows −

Output

1 3 5 7 9

HashMap in Java

A HashMap in Java is implemented using an array of linked lists. It has key-value pairs i.e. keys that are associated with the values and the keys are in arbitrary order. A HashMap can only have unique elements and can have only one null key but multiple null elements.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.*;
import java.lang.*;
import java.io.*;
public class Demo {
   public static void main (String[] args) {
      HashMap<Integer, String> hMap = new HashMap<Integer, String>();
      int[] arr = {1, 3, 5, 7, 9};
      for (int i : arr) {
         hMap.put(i, Integer.toString(i));  
      }
      for (int j: hMap.keySet()) {
         System.out.print(j + " ");
      }
   }
}

The output of the above program is as follows −

Output

1 3 5 7 9

LinkedHashMap in Java

A LinkedHashMap in Java is implemented using doubly linked buckets. It has key-value pairs i.e. keys that are associated with the values and the keys are ordered by their insertion order. A LinkedHashMap can only have unique elements and can have only one null key but multiple null elements.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.*;
import java.lang.*;
import java.io.*;
public class Demo {
   public static void main (String[] args) {
      LinkedHashMap<Integer, String> lhMap = new LinkedHashMap<Integer, String>();
      int[] arr = {1, 3, 5, 7, 9};
      for (int i : arr) {
         lhMap.put(i, Integer.toString(i));
      }
      for (int j: lhMap.keySet()) {
         System.out.print(j + " ");
      }
   }
}

The output of the above program is as follows −

Output

1 3 5 7 9
raja
Published on 28-Feb-2019 07:45:46
Advertisements