Online Tutorials & Training Materials | STechies.com
Register Login

HashMap vs Hashtable vs TreeMap vs LinkedHashMap

|| 0

HashMap vs Hashtable vs TreeMap vs LinkedHashMap
Stechies

This tutorial explains the what are the various data structure and differences between those data structures in Java such as HashMap vs TreeMap vs Hashtable LinkedHashMap with programming examples. 

What is Hash Map in Java?

The Map interface of Java implements the HashMap class. It is a part of the java.util.package. In this class, key-value pairs are used to store data. The key needs to be known in order to access the value.

This is a class that uses the method of Hashing - a method of transforming a large string into a small string. HashMap extends a class called AbstractMap. Other important features of HashMap are:

  • It does not have any duplicate keys but may have duplicate values.
  • Serializable and Clonable are implemented by HashMap.
  • It permits null keys and null values.
  • No assurance is provided whether elements will remain in the same order as they were inserted.

Example of Hash Map

import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;

public class Details {
   public static void main(String args[]) {
            HashMap<Integer, String> hsap = new HashMap<Integer, String>();
      hsap.put(1, "Chave");
      hsap.put(2, "Rohtas");
      hsap.put(8, "sohrab ");
      hsap.put(9, "vijay");
      hsap.put(3, "Ahuja");
   Set set = hsap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry mentry = (Map.Entry)iterator.next();
         System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
         System.out.println(mentry.getValue());
      }
      String var= hsap.get(2);
      System.out.println("indexd value 2 is: "+ var);
           hsap.remove(3);
      System.out.println("Map key and values after indexed removal:");
      Set set2 = hsap.entrySet();
      Iterator iterator2 = set2.iterator();
      while(iterator2.hasNext()) {
          Map.Entry mentry2 = (Map.Entry)iterator2.next();
          System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
          System.out.println(mentry2.getValue());
       }
   }
}

Output is

key is: 1 & Value is: Chave
key is: 2 & Value is: Rohtas
key is: 3 & Value is: Ahuja
key is: 8 & Value is: sohrab
key is: 9 & Value is: vijay
indexd value 2 is: Rohtas

Map key and values after indexed removal:

Key is: 1 & Value is: Chave
Key is: 2 & Value is: Rohtas
Key is: 8 & Value is: sohrab
Key is: 9 & Value is: vijay

What is Tree Map in Java?

The TreeMap is also an implementation of the Map interface of Java. The NavigableMap interface is implemented by this class. It is a class that is also a component of the Java Collections framework.

Unlike the HashMap, the TreeMap is a sorted collection based on the ordering of the keys in ascending order. This ordering can also sometimes depend upon the custom Comparator that is used while creating the TreeMap. Other salient features of a TreeMap are:

  • It does not contain duplicate keys.
  • It extends AbstractMap and implements SortedMap.
  • It is an unsynchronized class and is not safe for threaded environments.
  • It may have null values but no null keys.

Example of Tree Map

import java.util.*; 
public class TMap{ 
 public static void main(String args[]){ 
   TreeMap<Integer,String> map1=new TreeMap<Integer,String>();   
      map1.put(10,"Amitabha");   
      map1.put(50,"Jaya");   
      map1.put(30,"Abhishek");   
      map1.put(40,"Ashwarya");   
        for(Map.Entry m:map1.entrySet()){   
       System.out.println(m.getKey()+" "+m.getValue());   
      }   
 } 
} 

Output

$javac TMap.java
$java -Xmx128M -Xms16M TMap

10 Amitabha
30 Abhishek
40 Ashwarya
50 Jaya

What is Hash Table in Java?

The HashTable is a class that implements a Hashtable. This table maps the keys to their respective values. This class implements the Map interface. The Equals and the hashCode method are implemented by the objects when they are stored or taken out from the Hashtable. Other salient features of a HashTable are:

  • It stores elements that are unique and no duplicates are allowed.
  • It is a synchronized class.
  • No null values or keys are allowed inside a HashTable.
  • It inherits the Dictionary class.
  • It uses Hashtable() as its default constructor and has 11 as its default capacity.

Example Program for Hash Table

import java.util.*; 
public class Hstable{ 
 public static void main(String args[]){ 
  Hashtable<Integer,String> ht=new Hashtable<Integer,String>(); 
  ht.put(110,"Ronak"); 
  ht.put(112,"javed"); 
  ht.put(111,"babua"); 
  ht.put(113,"jassi"); 
  for(Map.Entry m:ht.entrySet()){ 
   System.out.println(m.getKey()+" "+m.getValue()); 
  } 
 } 
} 

Output

$javac Hstable.java
$java -Xmx128M -Xms16M Hstable
113 jassi
112 javed
111 babua
110 Ronak

What is LinkedHashMap in Java?

The LinkedHashMap is an implementation of the Map interface that is a Hash table and a Doubly Linked list. It implements the Map interface and inherits the HashMap class. The elements inserted here have an order.

The order of insertion can be used by the elements and they can be accessed based on that order. Some of the other important features of LinkedHashMap are:

  • It can have null keys and null values.
  • It does not have duplicate keys.
  • The iteration order of the elements is can be predicted.
  • As it is unsynchronized, it is not ideal for multi-threaded environments.
  • The default capacity is 16. It has a load factor of 0.75.
  • It provides the facility of changing the insertion order of elements through a constructor.

Example Program of Linkedhashmap

import java.util.LinkedHashMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;

public class LHMDemo {

    public static void main(String args[]) {
      LinkedHashMap<Integer, String> hmd =
                 new LinkedHashMap<Integer, String>();
         hmd.put(10, "jai");
         hmd.put(30, "Vikas");
         hmd.put(12, "Shelly");
         hmd.put(1, "Shivek");
         hmd.put(20, "Jhon");
         Set set = hmd.entrySet();
         Iterator iterator = set.iterator();
         while(iterator.hasNext()) {
            Map.Entry me = (Map.Entry)iterator.next();
            System.out.print("Key is: "+ me.getKey() +
                    "& Value is: "+me.getValue()+"n");
         }
    }
}

Output

$javac LHMDemo.java
$java -Xmx128M -Xms16M LHMDemo
Key is: 10& Value is: jai
Key is: 30& Value is: Vikas
Key is: 12& Value is: Shelly
Key is: 1& Value is: Shivek
Key is: 20& Value is: Jhon

Summary of differences between HashMap, LinkedHashMap, and TreeMap in Java

HashMap

TreeMap

LinkedHasMap

The iteration order is random.

Elements are sorted according to the natural order of the keys.

Elements are sorted based on the order they were inserted in the first place.

It permits null keys and null values.

It may have null values but no null keys.

It can have null keys and null values.

It does not have any duplicate keys, but may have duplicate values.

It does not contain duplicate keys.

It does not have duplicate keys.

It is an implementation of the Map interface.

It implements Map, NavigableMap and SortedMap.

It is an implementation of the Map interface.

The data structure used here is a list of buckets.

Red Black Tree implementation of Binary Tree.

HashTable and LinkedList through doubly linked buckets

Used for general purpose hashing for storing key-value pairs in a hash table.

Best when the keys need to be stored in a sorted order.

Mostly used in LRU caches (Least Recently Used) caches.


Related Articles