Skip to content
Related Articles

Related Articles

Improve Article
Hashing in Java
  • Difficulty Level : Medium
  • Last Updated : 19 Mar, 2019

In hashing there is a hash function that maps keys to some values. But these hashing function may lead to collision that is two or more keys are mapped to same value. Chain hashing avoids collision. The idea is to make each cell of hash table point to a linked list of records that have same hash function value.

Let’s create a hash function, such that our hash table has ‘N’ number of buckets.
To insert a node into the hash table, we need to find the hash index for the given key. And it could be calculated using the hash function.
Example: hashIndex = key % noOfBuckets

Insert: Move to the bucket corresponds to the above calculated hash index and insert the new node at the end of the list.

Delete: To delete a node from hash table, calculate the hash index for the key, move to the bucket corresponds to the calculated hash index, search the list in the current bucket to find and remove the node with the given key (if found).

Please refer Hashing | Set 2 (Separate Chaining) for details.

Methods to implement Hashing in Java

  1. With help of HashTable (A synchronized implementation of hashing)

    // Java program to demonstrate working of HashTable
    import java.util.*;
    class GFG {
        public static void main(String args[])
            // Create a HashTable to store 
            // String values corresponding to integer keys
            Hashtable<Integer, String>
                hm = new Hashtable<Integer, String>();
            // Input the values
            hm.put(1, "Geeks");
            hm.put(12, "forGeeks");
            hm.put(15, "A computer");
            hm.put(3, "Portal");
            // Printing the Hashtable
    {15=A computer, 3=Portal, 12=forGeeks, 1=Geeks}

  2. With the help of HashMap (A non-synchronized faster implementation of hashing)

    // Java program to create HashMap from an array
    // by taking the elements as Keys and
    // the frequencies as the Values
    import java.util.*;
    class GFG {
        // Function to create HashMap from array
        static void createHashMap(int arr[])
            // Creates an empty HashMap
            HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>();
            // Traverse through the given array
            for (int i = 0; i < arr.length; i++) {
                // Get if the element is present
                Integer c = hmap.get(arr[i]);
                // If this is first occurrence of element
                // Insert the element
                if (hmap.get(arr[i]) == null) {
                    hmap.put(arr[i], 1);
                // If elements already exists in hash map
                // Increment the count of element by 1
                else {
                    hmap.put(arr[i], ++c);
            // Print HashMap
        // Driver method to test above method
        public static void main(String[] args)
            int arr[] = { 10, 34, 5, 10, 3, 5, 10 };
    {34=1, 3=1, 5=2, 10=3}

  3. With the help of LinkedHashMap (Similar to HashMap, but keeps order of elements)

    // Java program to demonstrate working of LinkedHashMap 
    import java.util.*; 
    public class BasicLinkedHashMap 
        public static void main(String a[]) 
            LinkedHashMap<String, String> lhm = 
                           new LinkedHashMap<String, String>(); 
            lhm.put("one", ""); 
            lhm.put("two", ""); 
            lhm.put("four", ""); 
            // It prints the elements in same order  
            // as they were inserted     
            System.out.println("Getting value for key 'one': " 
                                           + lhm.get("one")); 
            System.out.println("Size of the map: " + lhm.size()); 
            System.out.println("Is map empty? " + lhm.isEmpty()); 
            System.out.println("Contains key 'two'? "+  
            System.out.println("Contains value 'practice.geeks"
            +"'? "+ lhm.containsValue("practice"
            System.out.println("delete element 'one': " +  
    Getting value for key 'one':
    Size of the map: 3
    Is map empty? false
    Contains key 'two'? true
    Contains value ''? true
    delete element 'one':

  4. With the help of ConcurretHashMap(Similar to Hashtable, Synchronized, but faster as multiple locks are used)

    // Java program to demonstrate working of ConcurrentHashMap
    import java.util.concurrent.*;
    class ConcurrentHashMapDemo {
        public static void main(String[] args)
            ConcurrentHashMap<Integer, String> m = 
                       new ConcurrentHashMap<Integer, String>();
            m.put(100, "Hello");
            m.put(101, "Geeks");
            m.put(102, "Geeks");
            // Printing the ConcurrentHashMap
            System.out.println("ConcurentHashMap: " + m);
            // Adding Hello at 101 key
            // This is already present in ConcurrentHashMap object
            // Therefore its better to use putIfAbsent for such cases
            m.putIfAbsent(101, "Hello");
            // Printing the ConcurrentHashMap
            System.out.println("\nConcurentHashMap: " + m);
            // Trying to remove entry for 101 key
            // since it is present
            m.remove(101, "Geeks");
            // Printing the ConcurrentHashMap
            System.out.println("\nConcurentHashMap: " + m);
            // replacing the value for key 101
            // from "Hello" to "For"
            m.replace(100, "Hello", "For");
            // Printing the ConcurrentHashMap
            System.out.println("\nConcurentHashMap: " + m);

    ConcurentHashMap: {100=Hello, 101=Geeks, 102=Geeks}
    ConcurentHashMap: {100=Hello, 101=Geeks, 102=Geeks}
    ConcurentHashMap: {100=Hello, 102=Geeks}
    ConcurentHashMap: {100=For, 102=Geeks}

  5. With the help of HashSet (Similar to HashMap, but maintains only keys, not pair)

    // Java program to demonstrate working of HashSet
    import java.util.*;
    class Test {
        public static void main(String[] args)
            HashSet<String> h = new HashSet<String>();
            // Adding elements into HashSet usind add()
            h.add("South Africa");
            h.add("India"); // adding duplicate elements
            // Displaying the HashSet
            // Checking if India is present or not
            System.out.println("\nHashSet contains India or not:"
                               + h.contains("India"));
            // Removing items from HashSet using remove()
            // Printing the HashSet
            System.out.println("\nList after removing Australia:" + h);
            // Iterating over hash set items
            System.out.println("\nIterating over list:");
            Iterator<String> i = h.iterator();
            while (i.hasNext())
    [South Africa, Australia, India]
    HashSet contains India or not:true
    List after removing Australia:[South Africa, India]
    Iterating over list:
    South Africa

  6. With the help of LinkedHashSet (Similar to LinkedHashMap, but maintains only keys, not pair)

    // Java program to demonstrate working of LinkedHashSet
    import java.util.LinkedHashSet;   
    public class Demo  
        public static void main(String[] args)  
            LinkedHashSet<String> linkedset =  
                               new LinkedHashSet<String>();   
            // Adding element to LinkedHashSet   
            // This will not add new element as A already exists  
            System.out.println("Size of LinkedHashSet = "
            System.out.println("Original LinkedHashSet:" + linkedset);   
            System.out.println("Removing D from LinkedHashSet: "
            System.out.println("Trying to Remove Z which is not "
                                "present: " + linkedset.remove("Z"));   
            System.out.println("Checking if A is present=" +  
            System.out.println("Updated LinkedHashSet: " + linkedset);   
    Size of LinkedHashSet = 5
    Original LinkedHashSet:[A, B, C, D, E]
    Removing D from LinkedHashSet: true
    Trying to Remove Z which is not present: false
    Checking if A is present=true
    Updated LinkedHashSet: [A, B, C, E]
  7. With the help of TreeSet (Implements the SortedSet interface, Objects are stored in a sorted and ascending order).

    // Java program to demonstrate working of TreeSet
    import java.util.*; 
    class TreeSetDemo { 
        public static void main(String[] args) 
            TreeSet<String> ts1 = new TreeSet<String>(); 
            // Elements are added using add() method 
            // Duplicates will not get insert 
            // Elements get stored in default natural 
            // Sorting Order(Ascending) 
            System.out.println("TreeSet: " + ts1); 
            // Checking if A is present or not
            System.out.println("\nTreeSet contains A or not:"
                               + ts1.contains("A"));
            // Removing items from TreeSet using remove()
            // Printing the TreeSet
            System.out.println("\nTreeSet after removing A:" + ts1);
            // Iterating over TreeSet items
            System.out.println("\nIterating over TreeSet:");
            Iterator<String> i = ts1.iterator();
            while (i.hasNext())


    TreeSet: [A, B, C]
    TreeSet contains A or not:true
    TreeSet after removing A:[B, C]
    Iterating over TreeSet:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes 

My Personal Notes arrow_drop_up
Recommended Articles
Page :