6 ways to implement Hashing in Java [Practical Examples]

Different methods to implement Hashing in Java

Hashing is a technique that maps values to the key using some hash function. This helps in making searching and accessing faster. However, there is one disadvantage of hashing is that it leads to the collision when two or more keys point to the same value in the hash table.
In order to implement hashing in java, we will use different classes as listed below.

Here, we will see the implementation of each of this with an example.

Advertisement
  • Using Hashtable Class
  • Using HashMap Class
  • Using LinkedHashMap Class
  • Using ConcurrentHashMap Class
  • Using HashSet Class
  • Using LinkedHashSet Class

 

Method-1: Using Hashtable Class

In this approach, we will use Hashtable class to implement Hashing in java. The Hashtable class of java.util package implements a hash table that maps keys to values. Any non null object can be used as a key or as a value. Moreover, the objects used as keys must implement the hashCode method and the equals method. This is a synchronized implementation of hashing.

Example : In this example, we are adding three key value pair to the hash table. Thereafter, we are getting the size, retrieving the value, and checking for the presence of the key in the hashtable.

// Program to implement hashing in java 
import java.util.Hashtable;
public class Main {
    public static void main(String[] args) {
        // Create an empty Hashtable
        Hashtable h = new Hashtable();

        // Add elements to the hashtable
        h.put("Computer", 10);
        h.put("Information Technology", 30);
        h.put("Electrical", 20);

        // Print size and content
        System.out.println("Size of hash table is:- " + h.size());
        System.out.println(h);

        //Checking for the presence of key
        System.out.println("Does hashtable contains Computer? " + h.containsKey("Computer"));
        System.out.println("Does hashtable contains Computer? " + h.containsKey("computer"));

        // Printing the value for the key
        System.out.println("value for key Electrical is " + h.get("Electrical"));
    }
}

Output

Size of hash table is:- 3
{Information Technology=30, Electrical=20, Computer=10}
Does hashtable contains Computer? true
Does hashtable contains Computer? false
value for key Electrical is 20

 

Method-2: Using HashMap Class

The HashMap class of java.util package implements a hash table that maps keys to values. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs, and we can access them by an index of another type. The HashMap is asynchronized implementation of hashing. So, this is faster as compared to the Hashtable. Unlike Hashtable, it allows to store the null keys as well, but there should be only one null key object and there can be any number of null values.

Example : In this example, we are adding three key value pair to the hashmap. Thereafter, we are getting the size, retrieving the value, and checking for the presence of the key in the hashmap.

// Program to implement hashing in java  
import java.util.HashMap;
public class Main {
    public static void main(String[] args) {
        HashMap h = new HashMap();

        // Add elements to the hashmap
        h.put("Computer", 10);
        h.put("Information Technology", 30);
        h.put("Electrical", 20);

        // Print size and content
        System.out.println("Size is:- " + h.size());
        System.out.println(h);

        //Checking for the presence of key
        System.out.println("Does hashmap contains Computer? " + h.containsKey("Computer"));
        System.out.println("Does hashmap contains Computer? " + h.containsKey("computer"));

        // Printing the value for the key
        System.out.println("value for key Electrical is " + h.get("Electrical"));
    }
}

Output

Advertisement
Size is:- 3
{Computer=10, Electrical=20, Information Technology=30}
Does hashmap contains Computer? true
Does hashmap contains Computer? false
value for key Electrical is 20

 

Method-3: Using LinkedHashMap Class

The LinkedHashMap class of java.util package implements the Hash table using the doubly linked list with predictable iteration order. The basic difference between HashMap and LinkedHashMap is it maintains a doubly-linked list and defines the iteration ordering, which is normally the order in which keys were inserted into the map. So, if a key is re-inserted into the map and thereafter if we invoke get method to get its value, then it will return the value of the last inserted duplicate key.

Example : In this example, we are adding three key value pair to the LinkedHashMap. Thereafter, we are inserting a duplicate key computer with the value 5. As we can see, while retrieving the value of the key computer, it returns the last updated value. Also, we are getting the size and checking for the presence of the key in the LinkedHashMap.

// Program to implement hashing in java 
import java.util.LinkedHashMap;
public class Main {
    public static void main(String[] args) {
        LinkedHashMap h = new LinkedHashMap();

        // Add elements to the LinkedHashMap
        h.put("Computer", 10);
        h.put("Information Technology", 30);
        h.put("Electrical", 20);
        h.put("Computer", 5);

        // Print size and content
        System.out.println("Size is:- " + h.size());
        System.out.println(h);

        //Checking for the presence of key
        System.out.println("Does LinkedHashMap contains Computer? " + h.containsKey("Computer"));
        System.out.println("Value for key Computer is  " + h.get("Computer"));

        // Printing the value for the key
        System.out.println("value for key Electrical is " + h.get("Electrical"));
    }
}

Output

Size is:- 3
{Computer=5, Information Technology=30, Electrical=20}
Does LinkedHashMap contains Computer? true
Value for key Computer is  5
value for key Electrical is 20

 

Method-4: Using ConcurrentHashMap Class

In this approach, we will use ConcurrentHashMap class to implement Hashing in java. The ConcurrentHashMap class of java.util.concurrent package implements a hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class has many similarities with the Hashtable class. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is no support for locking the entire table in a way that prevents all access. Hence, while working with the threads, it is better to choose ConcurrentHashMap over HashMap class.

Example : In this example, we are adding three key value pair to the ConcurrentHashMap. Thereafter, we are trying to insert a duplicate key computer with the value 5. As we can see, while retrieving the value of the key computer. Here, it returns the last updated value because rather than making separate entry, it overwrites the value of existing key. Also, we are getting the size and checking for the presence of the key in the LinkedHashMap.

// Program to implement hashing in java 
import java.util.concurrent.ConcurrentHashMap;
public class Main {
    public static void main(String[] args) {
        ConcurrentHashMap h = new ConcurrentHashMap();

        // Add elements to the ConcurrentHashMap
        h.put("Computer", 10);
        h.put("Information Technology", 30);
        h.put("Electrical", 20);

        // This will overwrite the value 10
        h.put("Computer", 5);

        // Print size and content
        System.out.println("Size is:- " + h.size());
        System.out.println(h);

        //Checking for the presence of key
        System.out.println("Does ConcurrentHashMap contains Computer? " + h.containsKey("Computer"));
        System.out.println("Value for key Computer is  " + h.get("Computer"));

        // Printing the value for the key
        System.out.println("value for key Electrical is " + h.get("Electrical"));
    }
}

Output

Advertisement
Size is:- 3
{Computer=5, Electrical=20, Information Technology=30}
Does ConcurrentHashMap contains Computer? true
Value for key Computer is  5
value for key Electrical is 20

 

Method-5: Using HashSet Class

In this approach, we will use HashSet class to implement Hashing in java. The HashSet class of java.util package implements the Set interface, backed by a hash table which is actually a HashMap instance. The class does not guarantee the constant order of elements over time. Moreover, this implementation is not synchronized. So, if multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.

Example : In this example, we are adding three values to the HashSet. Thereafter, we are retrieving the values using the iterator and next method of iterator.

 // Program to implement hashing in java 
 import java.util.HashSet;
 import java.util.Iterator;
 public class Main {
     public static void main(String[] args) {
         HashSet h = new HashSet();

         // Add elements to the HashSet
         h.add("Computer");
         h.add("Information Technology");
         h.add("Electrical");

         // Print size and content
         System.out.println("Size is:- " + h.size());
         Iterator i = h.iterator();
         while (i.hasNext())
             System.out.println(i.next());

         //Checking for the presence of key
         System.out.println("Does HashSet contains Computer? " + h.contains("Computer"));
     }
 }

Output

Size is:- 3
Computer
Electrical
Information Technology
Does HashSet contains Computer? true

 

Method-6: Using LinkedHashSet Class

In this approach, we will use LinkedHashSet class to implement Hashing in java. The LinkedHashSet class of java.util package implements the Hash table using the doubly linked list with predictable iteration order. The basic difference between HashSet and LinkedHashSet is it maintains a doubly-linked list and defines the iteration ordering, which is normally the order in which keys were inserted into the set. So, if a key is re-inserted into the set and thereafter if we invoke get method to get its value, then it will return the value of the last inserted duplicate key.

Example : In this example, we are adding three values to the LinkedHashSet. Thereafter, we are retrieving the values using the iterator and next method of iterator.

  // Program to implement hashing in java 
  import java.util.LinkedHashSet;
  import java.util.Iterator;
  public class Main {
      public static void main(String[] args) {
          LinkedHashSet h = new LinkedHashSet();

          // Add elements to the LinkedHashSet
          h.add("Computer");
          h.add("Information Technology");
          h.add("Electrical");

          // Print size and content
          System.out.println("Size is:- " + h.size());
          Iterator i = h.iterator();
          while (i.hasNext())
              System.out.println(i.next());

          //Checking for the presence of key
          System.out.println("Does LinkedHashSet contains Computer? " + h.contains("Computer"));
      }
  }

Output

Advertisement
Size is:- 3
Computer
Information Technology
Electrical
Does LinkedHashSet contains Computer? true

 

Summary

The knowledge of hashing in Java is very useful while working on real time applications. In this tutorial, we covered the six different ways to implement hashing in Java. As per the requirement of an application, we can choose the synchronized or asynchronized version of hashing to store the key value pairs. We learned in detail about hashing with an example.

All in all, this tutorial, covers everything that you need to know in order to have a clear view on implementing hashing in Java.

 

References

Hashtable Class
HashMap Class
LinkedHashMap Class
ConcurrentHashMap Class
HashSet Class
LinkedHashSet Class

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X