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)
- 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 Valuesimportjava.util.*;classGFG {// Function to create HashMap from arraystaticvoidcreateHashMap(intarr[]){// Creates an empty HashMapHashMap<Integer, Integer> hmap =newHashMap<Integer, Integer>();// Traverse through the given arrayfor(inti =0; i < arr.length; i++) {// Get if the element is presentInteger c = hmap.get(arr[i]);// If this is first occurrence of element// Insert the elementif(hmap.get(arr[i]) ==null) {hmap.put(arr[i],1);}// If elements already exists in hash map// Increment the count of element by 1else{hmap.put(arr[i], ++c);}}// Print HashMapSystem.out.println(hmap);}// Driver method to test above methodpublicstaticvoidmain(String[] args){intarr[] = {10,34,5,10,3,5,10};createHashMap(arr);}}chevron_rightfilter_noneOutput:{34=1, 3=1, 5=2, 10=3} - With the help of LinkedHashMap (Similar to HashMap, but keeps order of elements)
// Java program to demonstrate working of LinkedHashMapimportjava.util.*;publicclassBasicLinkedHashMap{publicstaticvoidmain(String a[]){LinkedHashMap<String, String> lhm =newLinkedHashMap<String, String>();lhm.put("one","practice.geeksforgeeks.org");lhm.put("two","code.geeksforgeeks.org");lhm.put("four","quiz.geeksforgeeks.org");// It prints the elements in same order// as they were insertedSystem.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);}}chevron_rightfilter_noneOutput:{one=practice.geeksforgeeks.org, two=code.geeksforgeeks.org, four=quiz.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=quiz.geeksforgeeks.org} - With the help of ConcurretHashMap(Similar to Hashtable, Synchronized, but faster as multiple locks are used)
// Java program to demonstrate working of ConcurrentHashMapimportjava.util.concurrent.*;classConcurrentHashMapDemo {publicstaticvoidmain(String[] args){ConcurrentHashMap<Integer, String> m =newConcurrentHashMap<Integer, String>();m.put(100,"Hello");m.put(101,"Geeks");m.put(102,"Geeks");// Printing the ConcurrentHashMapSystem.out.println("ConcurentHashMap: "+ m);// Adding Hello at 101 key// This is already present in ConcurrentHashMap object// Therefore its better to use putIfAbsent for such casesm.putIfAbsent(101,"Hello");// Printing the ConcurrentHashMapSystem.out.println("\nConcurentHashMap: "+ m);// Trying to remove entry for 101 key// since it is presentm.remove(101,"Geeks");// Printing the ConcurrentHashMapSystem.out.println("\nConcurentHashMap: "+ m);// replacing the value for key 101// from "Hello" to "For"m.replace(100,"Hello","For");// Printing the ConcurrentHashMapSystem.out.println("\nConcurentHashMap: "+ m);}}chevron_rightfilter_noneOutput: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 program to demonstrate working of HashSetimportjava.util.*;classTest {publicstaticvoidmain(String[] args){HashSet<String> h =newHashSet<String>();// Adding elements into HashSet usind add()h.add("India");h.add("Australia");h.add("South Africa");h.add("India");// adding duplicate elements// Displaying the HashSetSystem.out.println(h);// Checking if India is present or notSystem.out.println("\nHashSet contains India or not:"+ h.contains("India"));// Removing items from HashSet using remove()h.remove("Australia");// Printing the HashSetSystem.out.println("\nList after removing Australia:"+ h);// Iterating over hash set itemsSystem.out.println("\nIterating over list:");Iterator<String> i = h.iterator();while(i.hasNext())System.out.println(i.next());}}chevron_rightfilter_noneOutput:[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 program to demonstrate working of LinkedHashSetimportjava.util.LinkedHashSet;publicclassDemo{publicstaticvoidmain(String[] args){LinkedHashSet<String> linkedset =newLinkedHashSet<String>();// Adding element to LinkedHashSetlinkedset.add("A");linkedset.add("B");linkedset.add("C");linkedset.add("D");// This will not add new element as A already existslinkedset.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);}}chevron_rightfilter_noneOutput: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]
- Hashing | Set 1 (Introduction)
- Applications of Hashing
- Coalesced hashing
- Double Hashing
- Hashing | Set 2 (Separate Chaining)
- C++ program for hashing with chaining
- Hashing | Set 3 (Open Addressing)
- Practice Problems on Hashing
- Address Calculation Sort using Hashing
- Union and Intersection of two linked lists | Set-3 (Hashing)
- Cuckoo Hashing - Worst case O(1) Lookup!
- Top 20 Hashing Technique based Interview Questions
- Convert an array to reduced form | Set 1 (Simple and Hashing)
- Index Mapping (or Trivial Hashing) with negatives allowed
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in 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); } } |
{15=A computer, 3=Portal, 12=forGeeks, 1=Geeks}
Recommended Posts:
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



