How to Iterate Through HashTable in Java?
Last Updated :
24 Oct, 2021
HashTable is an underlying data structure where the insertion order in HashTable is not preserved, and it is based on the hashcode of keys. Duplicates keys are not allowed, but values can be duplicated. Heterogeneous objects are allowed for both keys and values. Value null is not allowed for both key and value otherwise we will get RunTimeException saying NullPointerException. It implements serializable and cloneable interfaces but not RandomAccess. Every method inside it is synchronized and hence HashTable objects are thread-safe. HashTable is the best choice if our frequent operation is search operation.
Methods:
There are various ways by which we can iterate through the HashTable which are as follows:
- Using Enumeration Interface
- Using keySet() method of Map and Enhance for loop
- Using keySet() method of Map and Iterator Interface
- Using entrySet() method of Map and enhanced for loop
- Using entrySet() method of Map and Iterator interface
- Using Iterable.forEach() method from version Java 8
Now let us discuss the internal implementation of all methods one by one in detail to get a better understanding of iteration through HashTable
Method 1: Using Enumeration Interface
java.util.Enumeration interface is one of the predefined interfaces, whose object is used for retrieving the data from collections framework variable. In a forward direction only and not in the backward direction. This interface has been superseded by an iterator.
Java
// Java Program to Iterate through HashTable
// using enumeration interface
// Importing required packages
import java.util.*;
import java.util.Enumeration;
// MAin Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating Hashtable object where key is of Integer
// type and value is of String type
Hashtable<Integer, String> ht = new Hashtable<>();
// Putting key-value pairs to HashTable object
// Custom input entries
ht.put(1, "Ram");
ht.put(2, "Shyam");
ht.put(3, "Bijay");
ht.put(4, "Hritik");
ht.put(5, "Piyush");
// Creating Enumeration interface
// and get keys() from Hashtable
Enumeration<Integer> e = ht.keys();
// Iterating through the Hashtable
// object
// Checking for next element in Hashtable object
// with the help of hasMoreElements() method
while (e.hasMoreElements()) {
// Getting the key of a particular entry
int key = e.nextElement();
// Print and display the Rank and Name
System.out.println("Rank : " + key
+ "\t\t Name : "
+ ht.get(key));
}
}
}
OutputRank : 5 Name : Piyush
Rank : 4 Name : Hritik
Rank : 3 Name : Bijay
Rank : 2 Name : Shyam
Rank : 1 Name : Ram
Method 2: Using keySet() method of Map and Enhance for loop
The java.util.HashMap.keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys, or we can create a new set and store the key elements in them.
Java
// Java program to iterate through HashTable
// using keySet method and enhance for-loop
// Importing required packages
import java.util.*;
import java.util.Set;
// Main Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating Hashtable object in where key is of
// Integer type
// and value is of String type
Hashtable<Integer, String> ht = new Hashtable<>();
// Putting key-value pairs to HashTable object
// custom entries
ht.put(1, "Java");
ht.put(2, "Scala");
ht.put(3, "Python");
ht.put(4, "Pearl");
ht.put(5, "R");
// Getting keySets of Hashtable and
// storing it into Set
Set<Integer> setOfKeys = ht.keySet();
// Iterating through the Hashtable
// object using for-Each loop
for (Integer key : setOfKeys) {
// Print and display the Rank and Name
System.out.println("Rank : " + key
+ "\t\t Name : "
+ ht.get(key));
}
}
}
OutputRank : 5 Name : R
Rank : 4 Name : Pearl
Rank : 3 Name : Python
Rank : 2 Name : Scala
Rank : 1 Name : Java
Method 3: Using keySet( ) method of Map and Iterator Interface
Again we will be using the same method as been implemented in the above example but here for iteration we will be using the Iterable interface
Java
// Java program to iterate through HashTable
// using keySet method and Iterator Interface
// Importing required libraries
import java.util.*;
import java.util.Iterator;
import java.util.Set;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating Hashtable object where key is of Integer
// type
// and value is of String type
Hashtable<Integer, String> ht = new Hashtable<>();
// Putting key-value pairs to HashTable object
// Custom input entries
ht.put(1, "Java");
ht.put(2, "Scala");
ht.put(3, "Python");
ht.put(4, "Pearl");
ht.put(5, "R");
// Getting keySets of Hashtable and
// storing it into Set
Set<Integer> setOfKeys = ht.keySet();
// Creating an Iterator object to
// iterate over the given Hashtable
Iterator<Integer> itr = setOfKeys.iterator();
// Iterating through the Hashtable object
// Checking for next element using hasNext() method
while (itr.hasNext()) {
// Getting key of a particular entry
int key = itr.next();
// Print and display the Rank and Name
System.out.println("Rank : " + key
+ "\t\t Name : "
+ ht.get(key));
}
}
}
OutputRank : 5 Name : R
Rank : 4 Name : Pearl
Rank : 3 Name : Python
Rank : 2 Name : Scala
Rank : 1 Name : Java
Method 4: Using entrySet() method of Map and enhanced for loop
The java.util.HashMap.entrySet() method in Java is used to create a set out of the same elements contained in the hash map. It basically returns a set view of the hash map, or we can create a new set and store the map elements into them.
Java
// Java program to iterate through HashTable
// using entrySet method and enhance for-loop
// Importing required libraries
import java.util.*;
import java.util.Map.Entry;
import java.util.Set;
// Main Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating Hashtable object where key is of Integer
// type and value is of String type
Hashtable<Integer, String> ht = new Hashtable<>();
// Putting key-value pairs to HashTable object
// Custom input entries
ht.put(1, "Java");
ht.put(2, "Scala");
ht.put(3, "Python");
ht.put(4, "Pearl");
ht.put(5, "R");
// Storing all entries of Hashtable
// in a Set using entrySet() method
Set<Entry<Integer, String> > entrySet
= ht.entrySet();
// Iterating through the Hashtable object
// using for-each loop
for (Entry<Integer, String> entry : entrySet) {
// print ad display the Rank and Name
System.out.println("Rank : " + entry.getKey()
+ "\t\t Name : "
+ entry.getValue());
}
}
}
OutputRank : 5 Name : R
Rank : 4 Name : Pearl
Rank : 3 Name : Python
Rank : 2 Name : Scala
Rank : 1 Name : Java
Method 5: Using entrySet() method of Map and Iterator interface
Again we will be using the same method as been implemented in the above example but here for iteration we will be using the Iterable interface
Java
// Java program to iterate through hashtable using
// entrySet method and Iterator interface
// Importing required libraries
import java.util.*;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
// Main Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating Hashtable object where key is of Integer
// type
// and value is of String type
Hashtable<Integer, String> ht = new Hashtable<>();
// Putting key-value pairs to Hashtable object
// Custom input entries
ht.put(1, "Java");
ht.put(2, "Scala");
ht.put(3, "Python");
ht.put(4, "Pearl");
ht.put(5, "R");
// Storing all entries of Hashtable in a Set
// using entrySet() method
Set<Entry<Integer, String> > entrySet
= ht.entrySet();
// Creating an Iterator object to
// iterate over the given Hashtable
Iterator<Entry<Integer, String> > itr
= entrySet.iterator();
// Iterating through the Hashtable object
// using iterator
// Checking for next element
// using hasNext() method
while (itr.hasNext()) {
// Getting a particular entry of HashTable
Entry<Integer, String> entry = itr.next();
// Print and display the Rank and Name
System.out.println("Rank : " + entry.getKey()
+ "\t\t Name : "
+ entry.getValue());
}
}
}
OutputRank : 5 Name : R
Rank : 4 Name : Pearl
Rank : 3 Name : Python
Rank : 2 Name : Scala
Rank : 1 Name : Java
6. Using Iterable.forEach() method from version Java 8
With the coming of havoc new features in version, 8. It has been Quite a while since Java 8 released. With the release, they have improved some existing APIs and added few new features. One of them is forEach() method in java.lang.Iterable Interface.
Java
// Java program to iterate through HashTable
// using Iterable forEach()method of java 8
// Import required libraries
import java.util.*;
// Main Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating Hashtable object in where key is of
// Integer type
// and value is of String type
Hashtable<Integer, String> ht = new Hashtable<>();
// Putting key-value pairs to HashTable object
// Custom input entries
ht.put(1, "Java");
ht.put(2, "Scala");
ht.put(3, "Python");
ht.put(4, "Ruby");
ht.put(5, "R");
// Iterating through Hashtable using
// forEach loop of java 8
ht.forEach((key, value)
-> System.out.println(
"Rank : " + key
+ "\t\t Name : " + value));
}
}
OutputRank : 1 Name : Java
Rank : 2 Name : Scala
Rank : 3 Name : Python
Rank : 4 Name : Ruby
Rank : 5 Name : R
Similar Reads
How to Iterate HashMap in Java?
HashMap is a part of Javaâs collection providing the basic implementation of the Map interface of Java by storing the data in (Key, Value) pairs to access them by an index of another type. One object is listed as a key (index) to another object (value). If you try to insert the duplicate key, it wil
5 min read
How to Iterate HashSet in Java?
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. It stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.Methods to Ite
3 min read
How to iterate LinkedHashMap in Java?
LinkedHashMap class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted. Th
2 min read
How to Create a Synchronized HashTable in Java?
In Java, a synchronized HashTable is achieved by wrapping a regular HashTable with the Collection.synchronizedMap( ) method. This wrapper ensures that each method of the Map interface is synchronized, making the HashTable thread-safe. Syntax:Map<KeyType, ValueType> synchronizedHashTable = Coll
3 min read
How to Iterate Over a HashSet Without an Iterator in Java?
In Java, we can iterate over a HashSet without using an Iterator. For this, we need two methods. We can directly loop through the elements of the HashSet. In this article, we will discuss the two methods to iterate over a HashSet without using Iterator. Program to Iterate over a HashSet without an I
2 min read
Java Program to Implement HashTable API
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. To implement Hashtable API f
4 min read
Traverse Through a HashMap in Java
HashMap stores the data in (Key, Value) pairs, and you can access them by an index of another type. HashMap class implements Map interface which allows us to store key. hashMap is a part of the java collections framework been up since Java 1.2. It internally uses hashing technique which is pretty fa
4 min read
How to Eliminate Duplicate Keys in Hashtable in Java?
HashTable class is part of the Collection framework in Java where the only major difference it has from HashMap is that it's synchronized. Hash table maps keys to values i.e. it internally uses buckets to store key-value pairs and the corresponding bucket to a key-value pair is determined by the key
4 min read
How to Convert a HashTable to Other Collections Types in Java?
In Java, a Hashtable is a data structure that stores the data in the form of key and value pairs. And each key is mapped to a specific value. It implements the Map interface. HashTable provides a simple way to access the data using the unique keys. In this article, we will learn how to convert a Has
3 min read
How to Convert a HashSet to JSON in Java?
In Java, a HashSet is an implementation of the Set interface that uses a hash table to store elements. It allows fast lookups and does not allow duplicate elements. Elements in a HashSet are unordered and can be of any object type. In this article, we will see how to convert a HashSet to JSON in Jav
2 min read