Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Differences between TreeMap, HashMap and LinkedHashMap in Java
Next article icon

Hashing in Java

Last Updated : 01 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  • With help of HashTable (A synchronized implementation of hashing)
Java
// 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         System.out.println(hm);     } } 

Output
{15=A computer, 3=Portal, 12=forGeeks, 1=Geeks}
  • With the help of HashMap (A non-synchronized faster implementation of hashing)
Java
// 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         System.out.println(hmap);     }      // Driver method to test above method     public static void main(String[] args)     {         int arr[] = { 10, 34, 5, 10, 3, 5, 10 };         createHashMap(arr);     } } 

Output
{34=1, 3=1, 5=2, 10=3}
  • With the help of LinkedHashMap (Similar to HashMap, but keeps order of elements)
Java
// 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", "practice.geeksforgeeks.org");          lhm.put("two", "code.geeksforgeeks.org");          lhm.put("four", "www.geeksforgeeks.org");             // It prints the elements in same order           // as they were inserted              System.out.println(lhm);             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'? "+                                     lhm.containsKey("two"));          System.out.println("Contains value 'practice.geeks"         +"forgeeks.org'? "+ lhm.containsValue("practice"+          ".geeksforgeeks.org"));          System.out.println("delete element 'one': " +                              lhm.remove("one"));          System.out.println(lhm);      }  }  

Output
{one=practice.geeksforgeeks.org, two=code.geeksforgeeks.org, four=www.geeksforgeeks.org} Getting value for key 'one': practice.geeksforgeeks.org Size of the map: 3 Is map empty? false Contains key 'two'? true Contains value 'practice.geeksforgeeks.org'? true delete element 'one': practice.geeksforgeeks.org {two=code.geeksforgeeks.org, four=www.geeksforgeeks.org}
  • With the help of ConcurretHashMap(Similar to Hashtable, Synchronized, but faster as multiple locks are used)
Java
// 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("ConcurrentHashMap: " + 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("\nConcurrentHashMap: " + m);          // Trying to remove entry for 101 key         // since it is present         m.remove(101, "Geeks");          // Printing the ConcurrentHashMap         System.out.println("\nConcurrentHashMap: " + m);          // replacing the value for key 101         // from "Hello" to "For"         m.replace(100, "Hello", "For");          // Printing the ConcurrentHashMap         System.out.println("\nConcurrentHashMap: " + m);     } } 

Output
ConcurentHashMap: {100=Hello, 101=Geeks, 102=Geeks}  ConcurentHashMap: {100=Hello, 101=Geeks, 102=Geeks}  ConcurentHashMap: {100=Hello, 102=Geeks}  ConcurentHashMap: {100=For, 102=Geeks}
  • With the help of HashSet (Similar to HashMap, but maintains only keys, not pair)
Java
// 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 using add()         h.add("India");         h.add("Australia");         h.add("South Africa");         h.add("India"); // adding duplicate elements          // Displaying the HashSet         System.out.println(h);          // Checking if India is present or not         System.out.println("\nHashSet contains India or not:"                            + h.contains("India"));          // Removing items from HashSet using remove()         h.remove("Australia");          // 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())             System.out.println(i.next());     } } 

Output
[South Africa, Australia, India]  HashSet contains India or not:true  List after removing Australia:[South Africa, India]  Iterating over list: South Africa India

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

Java
// 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            linkedset.add("A");            linkedset.add("B");            linkedset.add("C");            linkedset.add("D");              // This will not add new element as A already exists           linkedset.add("A");           linkedset.add("E");               System.out.println("Size of LinkedHashSet = " +                                      linkedset.size());            System.out.println("Original LinkedHashSet:" + linkedset);            System.out.println("Removing D from LinkedHashSet: " +                              linkedset.remove("D"));            System.out.println("Trying to Remove Z which is not "+                              "present: " + linkedset.remove("Z"));            System.out.println("Checking if A is present=" +                               linkedset.contains("A"));          System.out.println("Updated LinkedHashSet: " + linkedset);        }    }    

Output
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]
  • With the help of TreeSet (Implements the SortedSet interface, Objects are stored in a sorted and ascending order).
Java
// 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          ts1.add("A");          ts1.add("B");          ts1.add("C");             // Duplicates will not get insert          ts1.add("C");             // 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()         ts1.remove("A");          // 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())             System.out.println(i.next());     } } 

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

Next Article
Differences between TreeMap, HashMap and LinkedHashMap in Java

R

RishabhPrabhu
Improve
Article Tags :
  • Java
  • Hash
  • Java Programs
  • DSA
  • Java-HashMap
  • java-hashset
  • Java-LinkedHashMap
  • Java-HashTable
  • Java-ConcurrentHashMap
  • java-LinkedHashSet
Practice Tags :
  • Hash
  • Java

Similar Reads

    Java LinkedHashMap
    LinkedHashMap in Java implements the Map interface of the Collections Framework. It stores key-value pairs while maintaining the insertion order of the entries. It maintains the order in which elements are added.Stores unique key-value pairs.Maintains insertion order.Allows one null key and multiple
    7 min read
    Java LinkedHashMap clear() Method
    The clear() method in Java is a built-in method of the java.util.LinkedHashMap class. This method is used to remove all the key-value mappings from a LinkedHashMap. After invoking this method, the map becomes empty.This method is very helpful when we want to reuse an existing map object without crea
    2 min read
    LinkedHashMap containsKey() Method in Java with Examples
    The java.util.LinkedHashMap.containsKey() method is used to check whether a particular key is being mapped into the LinkedHashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.Syntax: Linked_Hash_Map.containsKey(key_element) Parameters: The met
    2 min read
    LinkedHashMap get() Method in Java with Examples
    In Java, get() method of LinkedHashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key. --> java.util Package --> LinkedHashMap Class --> get() Method Syntax: Linked_Hash_Ma
    2 min read
    LinkedHashMap removeEldestEntry() Method in Java
    The java.util.LinkedHashMap.removeEldestEntry() method in Java is used keep a track of whether the map removes any eldest entry from the map. So each time a new element is added to the LinkedHashMap, the eldest entry is removed from the map. This method is generally invoked after the addition of the
    3 min read
    LinkedHashMap and LinkedHashSet in Java
    The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements
    3 min read
    Design LRU Cache
    Design a data structure for LRU Cache. It should support the following operations: get and put.get(key) - Returns the value of the given key if it exists in the cache; otherwise, returns -1.put(key, value) - Inserts or updates the key-value pair in the cache. If the cache reaches capacity, remove th
    5 min read
    Hashing in Java
    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 fun
    6 min read
    Differences between TreeMap, HashMap and LinkedHashMap in Java
    Prerequisite: HashMap and TreeMap in Java TreeMap, HashMap and LinkedHashMap: What's Similar? All offer a key->value map and a way to iterate through the keys. The most important distinction between these classes is the time guarantees and the ordering of the keys.All three classes HashMap, TreeM
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences