Hashtable in Java
The Hashtable class implements a hash table, which maps keys to values. Any
non-null object can be used as a key or as a value. To successfully store and
retrieve objects from a hashtable, the objects used as keys must implement the
hashCode method and the equals method.
Declaration:
public class Hashtable<K,V> extends Dictionary<K,V> implements
Map<K,V>, Cloneable, Serializable
Type Parameters:
● K – the type of keys maintained by this map
● V – the type of mapped values
Constructors:
In order to create a Hashtable, we need to import it from java.util.Hashtable.
There are various ways in which we can create a Hashtable.
1. Hashtable(): This creates an empty hashtable.
Hashtable<K, V> ht = new Hashtable<K, V>();
● Java
// Java program to demonstrate
// adding elements to Hashtable
import java.io.*;
import java.util.*;
class AddElementsToHashtable {
public static void main(String args[])
{
// No need to mention the
// Generic type twice
Hashtable<Integer, String> ht1 = new Hashtable<>();
// Initialization of a Hashtable
// using Generics
Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>();
// Inserting the Elements
// using put() method
ht1.put(1, "one");
ht1.put(2, "two");
ht1.put(3, "three");
ht2.put(4, "four");
ht2.put(5, "five");
ht2.put(6, "six");
// Print mappings to the console
System.out.println("Mappings of ht1 : " + ht1);
System.out.println("Mappings of ht2 : " + ht2);
}
Output
Mappings of ht1 : {3=three, 2=two, 1=one}
Mappings of ht2 : {6=six, 5=five, 4=four}
2. Hashtable(int initialCapacity): This creates a hash table that has an initial
size specified by initialCapacity .
Hashtable<K, V> ht = new Hashtable<K, V>(int initialCapacity);
● Java
// Java program to demonstrate
// adding elements to Hashtable
import java.io.*;
import java.util.*;
class AddElementsToHashtable {
public static void main(String args[])
{
// No need to mention the
// Generic type twice
Hashtable<Integer, String> ht1 = new Hashtable<>(4);
// Initialization of a Hashtable
// using Generics
Hashtable<Integer, String> ht2
= new Hashtable<Integer, String>(2);
// Inserting the Elements
// using put() method
ht1.put(1, "one");
ht1.put(2, "two");
ht1.put(3, "three");
ht2.put(4, "four");
ht2.put(5, "five");
ht2.put(6, "six");
// Print mappings to the console
System.out.println("Mappings of ht1 : " + ht1);
System.out.println("Mappings of ht2 : " + ht2);
}
Output
Mappings of ht1 : {3=three, 2=two, 1=one}
Mappings of ht2 : {4=four, 6=six, 5=five}
3. Hashtable(Map<? extends K,? extends V> m): This creates a hash table
that is initialized with the elements in m.
Hashtable<K, V> ht = new Hashtable<K, V>(Map m);
● Java
// Java program to demonstrate
// adding elements to Hashtable
import java.io.*;
import java.util.*;
Continue from down below here next lesson
class AddElementsToHashtable {
public static void main(String args[])
{
// No need to mention the
// Generic type twice
Map<Integer, String> hm = new HashMap<>();
// Inserting the Elements
// using put() method
hm.put(1, "one");
hm.put(2, "two");
hm.put(3, "three");
// Initialization of a Hashtable
// using Generics
Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>(hm);
// Print mappings to the console
System.out.println("Mappings of ht2 : " + ht2);
}
Output
Mappings of ht2 : {3=three, 2=two, 1=one}
Example:
● Java
// Java program to illustrate
// Java.util.Hashtable
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Create an empty Hashtable
Hashtable<String, Integer> ht = new Hashtable<>();
// Add elements to the hashtable
ht.put("vishal", 10);
ht.put("sachin", 30);
ht.put("vaibhav", 20);
// Print size and content
System.out.println("Size of map is:- " + ht.size());
System.out.println(ht);
// Check if a key is present and if
// present, print value
if (ht.containsKey("vishal")) {
Integer a = ht.get("vishal");
System.out.println("value for key"
+ " \"vishal\" is:- " + a);
}
}
Output
Size of map is:- 3
{vaibhav=20, vishal=10, sachin=30}
value for key "vishal" is:- 10
Performing Various Operations on Hashtable
1. Adding Elements: In order to add an element to the hashtable, we can use
the put() method. However, the insertion order is not retained in the hashtable.
Internally, for every element, a separate hash is generated and the elements are
indexed based on this hash to make it more efficient.
● Java
// Java program to demonstrate
// adding elements to Hashtable
import java.io.*;
import java.util.*;
class AddElementsToHashtable {
public static void main(String args[])
{
// No need to mention the
// Generic type twice
Hashtable<Integer, String> ht1 = new Hashtable<>();
// Initialization of a Hashtable
// using Generics
Hashtable<Integer, String> ht2
= new Hashtable<Integer, String>();
// Inserting the Elements
// using put() method
ht1.put(1, "Geeks");
ht1.put(2, "For");
ht1.put(3, "Geeks");
ht2.put(1, "Geeks");
ht2.put(2, "For");
ht2.put(3, "Geeks");
// Print mappings to the console
System.out.println("Mappings of ht1 : " + ht1);
System.out.println("Mappings of ht2 : " + ht2);
}
}
Output
Mappings of ht1 : {3=Geeks, 2=For, 1=Geeks}
Mappings of ht2 : {3=Geeks, 2=For, 1=Geeks}
2. Changing Elements: After adding the elements if we wish to change the
element, it can be done by again adding the element with the put() method. Since
the elements in the hashtable are indexed using the keys, the value of the key
can be changed by simply inserting the updated value for the key for which we
wish to change.
● Java
// Java program to demonstrate
// updating Hashtable
import java.io.*;
import java.util.*;
class UpdatesOnHashtable {
public static void main(String args[])
{
// Initialization of a Hashtable
Hashtable<Integer, String> ht
= new Hashtable<Integer, String>();
// Inserting the Elements
// using put method
ht.put(1, "Geeks");
ht.put(2, "Geeks");
ht.put(3, "Geeks");
// print initial map to the console
System.out.println("Initial Map " + ht);
// Update the value at key 2
ht.put(2, "For");
// print the updated map
System.out.println("Updated Map " + ht);
}
Output
Initial Map {3=Geeks, 2=Geeks, 1=Geeks}
Updated Map {3=Geeks, 2=For, 1=Geeks}
3. Removing Element: In order to remove an element from the Map, we can use
the remove() method. This method takes the key value and removes the
mapping for a key from this map if it is present in the map.
● Java
// Java program to demonstrate
// the removing mappings from Hashtable
import java.io.*;
import java.util.*;
class RemovingMappingsFromHashtable {
public static void main(String args[])
{
// Initialization of a Hashtable
Map<Integer, String> ht
= new Hashtable<Integer, String>();
// Inserting the Elements
// using put method
ht.put(1, "Geeks");
ht.put(2, "For");
ht.put(3, "Geeks");
ht.put(4, "For");
// Initial HashMap
System.out.println("Initial map : " + ht);
// Remove the map entry with key 4
ht.remove(4);
// Final Hashtable
System.out.println("Updated map : " + ht);
}
Output
Initial map : {4=For, 3=Geeks, 2=For, 1=Geeks}
Updated map : {3=Geeks, 2=For, 1=Geeks}
4. Traversal of a Hashtable: To iterate the table, we can make use of
an advanced for loop. Below is the example of iterating a hashtable.
● Java
// Java program to illustrate
// traversal of Hashtable
import java.util.Hashtable;
import java.util.Map;
public class IteratingHashtable {
public static void main(String[] args)
{
// Create an instance of Hashtable
Hashtable<String, Integer> ht = new Hashtable<>();
// Adding elements using put method
ht.put("vishal", 10);
ht.put("sachin", 30);
ht.put("vaibhav", 20);
// Iterating using enhanced for loop
for (Map.Entry<String, Integer> e : ht.entrySet())
System.out.println(e.getKey() + " "
+ e.getValue());
}
Output
vaibhav 20
vishal 10
sachin 30
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 can be accessed in their insertion order.
// Java program to demonstrate working of LinkedHashMap
import java.util.*;
public class LinkedHashMapExample {
public static void main(String a[])
{
// create an instance of LinkedHashMap
LinkedHashMap<String, String> lhm
= new LinkedHashMap<String, String>();
// Add mappings using put method
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 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"));
// print mappings to the console
System.out.println("Mappings of LinkedHashMap : "
+ lhm);
}
}
Output
{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
Mappings of LinkedHashMap : {two=code.geeksforgeeks.org,
four=quiz.geeksforgeeks.org}
How to sort the Hashtable by values in Java?
The Hashtable class in Java does not maintain the order of its entries, so even if we sort
it, there is no guarantee that the elements will be returned in that order. We need to
convert a hashtable to a collection that maintains the element order.
How to sort Hashtable by values if you only want values?
We can get all the values from the hashtable using the values method, convert it to a
List (like ArrayList or LinkedList) and then we can sort the List using the sort method of
the Collections class as given below.
1 Hashtable<String, Integer> htRandomNumbers = new Hashtable<String, Integer>();
3 htRandomNumbers.put("Five", 5);
4 htRandomNumbers.put("Three", 3);
5 htRandomNumbers.put("Nine", 9);
6 htRandomNumbers.put("Seven", 7);
7 htRandomNumbers.put("Two", 2);
9 System.out.println( "Hashtable contains: " + htRandomNumbers );
10
11 /*
12 * Get all hashtable values using
13 * the value method and convert it
14 * to a List
15 */
16 List<Integer> list = new ArrayList<Integer>( htRandomNumbers.values() );
17
18 /*
19 * Sort the list using the sort method
20 * of the Collections class
21 */
22 Collections.sort(list);
23
24 System.out.println("Sorted values: " + list);
Output
1 Hashtable contains: {Seven=7, Three=3, Nine=9, Two=2, Five=5}
2 Sorted values: [2, 3, 5, 7, 9]
The sort method of the Collections class sorts the list elements in their natural order,
which is the ascending order for the type Integer. If you want to sort the values in
descending order, pass the reverse comparator in the sort method as given below.
1 Collections.sort(list, Collections.reverseOrder());
Output
1 Hashtable contains: {Seven=7, Three=3, Nine=9, Two=2, Five=5}
2 Sorted values: [9, 7, 5, 3, 2]
How to print LinkedHashMap in ascending order:-
LinkedHashMap maintains insertion order. Convert LinkedHashMap into
TreeMap and after that print keys of TreeMap which are sorted in nature.
Example:
Input: linkedHashMap = {{5,4}, {3,44}, {4,15}, {1,20}, {2,11}}
Output:
key -> 1 : value -> 20
key -> 2 : value -> 11
key -> 3 : value -> 44
key -> 4 : value -> 15
key -> 5: value -> 4
Approach:
1. Take LinkedHashMap as an input.
2. Create a new TreeMap.
3. Pass LinkedHashMap object into the constructor of TreeMap.
4. Print Keys of TreeMap object.
Below is the implementation of the above approach:
● Java
// Sort LinkedHashMap by keys in Java
import java.util.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
LinkedHashMap<Integer, Integer> lMap
= new LinkedHashMap<>();
// adding key-value pairs to LinkedHashMap
object
lMap.put(5, 4);
lMap.put(3, 44);
lMap.put(4, 15);
lMap.put(1, 20);
lMap.put(2, 11);
System.out.println("After Sorting :\n");
// convert to TreeMap
Map<Integer, Integer> map = new
TreeMap<>(lMap);
// iterate acc to ascending order of keys
for (Integer sKey : map.keySet()) {
System.out.println("Key -> " + sKey
+ ": Value -> "
+ lMap.get(sKey));
}
}
}
Output
After Sorting :
Key -> 1: Value -> 20
Key -> 2: Value -> 11
Key -> 3: Value -> 44
Key -> 4: Value -> 15
Key -> 5: Value -> 4