Write a Java program to iterate through all elements in a hash list

Java Collection, HashSet Exercises: Iterate through all elements in a hash list

Last update on December 14 2021 06:27:40 (UTC/GMT +8 hours)

Iterate through List in Java

Lists in java allow us to maintain an ordered collection of objects. Duplicate elements as well as null elements can also be stored in a List in Java. The List interface is a part of java.util package and it inherits the Collection interface. It preserves the order of insertion.

There are several ways to iterate over List in Java. They are discussed below:

Methods:

  1. Using loops (Naive Approach)
    • For loop
    • For-each loop
    • While loop
  2. Using Iterator
  3. Using List iterator
  4. Using lambda expression
  5. Using stream.forEach()

Method 1-A: Simple for loop

Each element can be accessed by iteration using a simple for loop. The index can be accessed using the index as a loop variable.



Syntax:

for (i = 0; i < list_name.size(); i++) { // code block to be executed }

Example




// Java Program to iterate over List
// Using simple for loop
// Importing all classes of
// java.util package
import java.util.*;
// CLass
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating a ArrayList
List<String> myList = new ArrayList<String>();
// Adding elements to the list
// Custom inputs
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
// For loop for iterating over the List
for (int i = 0; i < myList.size(); i++) {
// Print all elements of List
System.out.println(myList.get(i));
}
}
}
Output A B C D

Method 1-B: Enhanced for loop

Each element can be accessed by iteration using an enhanced for loop. This loop was introduced in J2SE 5.0. It is an alternative approach to traverse the for a loop. It makes the code more readable.

Syntax:

for(data_type variable : List_name) { // Body of the loop. // Each element can be accessed using variable. }




// Java Program to Iterate over a List
// using enhanced for loop (for-each)
// Importing all classes of
// java.util package
import java.util.*;
// Class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an Arraylist
List<String> myList = new ArrayList<String>();
// Adding elements to the List
// Custom inputs
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
// Using enhanced for loop(for-each) for iteration
for (String i : myList) {
// Print all elements of ArrayList
System.out.println(i);
}
}
}
Output A B C D

Method 1-C: Using a while loop

Iterating over a list can also be achieved using a while loop. The block of code inside the loop executes until the condition is true. A loop variable can be used as an index to access each element.

Syntax:

while(variable<list_name.size()) { // Block of code to be executed }




// Java Program to iterate over a List
// using while loop
// Importing all classes of
// java.util package
import java.util.*;
// Class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an ArrayList
List<String> myList = new ArrayList<String>();
// Adding elements to the List
// Custom inputs
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
// Initializing any variable to 0
int i = 0;
// If variable value is lesser than
// value indicating size of List
while (i < myList.size()) {
// Print element of list
System.out.println(myList.get(i));
// Increase variable count by 1
i++;
}
}
}
Output A B C D

Method 2: Using iterator

An iterator is an object in Java that allows iterating over elements of a collection. Each element in the list can be accessed using iterator with a while loop.

Syntax:

Iterator<data_type> variable = list_name.iterator();

Example




// Java Program to iterate over the list
// using iterator
// Importing all classes of
// java.util package
import java.util.*;
// Class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an ArrayList
List<String> myList = new ArrayList<String>();
// Adding elements to the List
// Custom inputs
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
// Iterator
Iterator<String> it = myList.iterator();
// Condition check for elements in List
// using hasNext() method returning true till
// there i single element in a List
while (it.hasNext()) {
// Print all elements of List
System.out.println(it.next());
}
}
}
Output A B C D

Method 3: Using List iterator

ListIterator is an iterator is a java which is available since the 1.2 version. It allows us to iterate elements one-by-one from a List implemented object. It is used to iterator over a list using while loop.

Syntax

ListIterator<data_type> variable = list_name.listIterator();




// Java program to iterate over a list
// using ListIterator
import java.util.*;
// Class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an ArrayList
List<String> myList = new ArrayList<String>();
// Adding elements to the List
// Custom inputs
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
// List iterator
ListIterator<String> it = myList.listIterator();
// Condition check whether there is element in List
// using hasNext() which holds true till
// there is single element in List
while (it.hasNext()) {
// Print all elements of List
System.out.println(it.next());
}
}
}
Output A B C D

Method 4: Using Iterable.forEach()

This feature is available since Java 8. It can also be used to iterate over a List. Iteration can be done using a lambda expression.

Syntax:

list_name.forEach(variable->{//block of code})




// Java Program to iterate over a List
// using forEach()
// Importing all classes of
// java.util method
import java.util.*;
// Class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an ArrayList
List<String> myList = new ArrayList<String>();
// Adding elements to the List
// Custom inputs
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
// Lambda expression printing all elements in a List
myList.forEach(
(temp) -> { System.out.println(temp); });
}
}
Output A B C D

Method 5: Using Stream.forEach()

The processing order of stream().forEach() is undefined while in case of forEach(), it is defined. Both can be used to iterate over a List.

Syntax:

list_name.stream.forEach(variable->{//block of code})




// Java Program iterating over a List
// using stream.forEach() method
// Importing all classes of
// java.util method
import java.util.*;
// Class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an ArrayList
List<String> myList = new ArrayList<String>();
// Adding elements to the List
// Custom inputs
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
// stream.forEach() method prints
// all elements inside a List
myList.stream().forEach(
(temp) -> System.out.println(temp));
}
}
Output A B C D

Write a Java program to iterate through all elements in a hash list




Article Tags :
Java
Java Programs
Java-Collections
java-list
Practice Tags :
Java
Java-Collections

How to Iterate Through HashTable in Java?

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:

  1. Using Enumeration Interface
  2. Using keySet() method of Map and Enhance for loop
  3. Using keySet() method of Map and Iterator Interface
  4. Using entrySet() method of Map and enhanced for loop
  5. Using entrySet() method of Map and Iterator interface
  6. 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 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));
}
}
}
Output Rank : 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 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));
}
}
}
Output Rank : 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 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));
}
}
}
Output Rank : 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 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());
}
}
}
Output Rank : 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 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());
}
}
}
Output Rank : 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 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));
}
}
Output Rank : 1 Name : Java Rank : 2 Name : Scala Rank : 3 Name : Python Rank : 4 Name : Ruby Rank : 5 Name : R

Write a Java program to iterate through all elements in a hash list




Article Tags :
Java
Java Programs
Java-Collections
Java-HashTable
Practice Tags :
Java
Java-Collections

Java Program to Iterate over a HashMap

In this example, we will learn to iterate over keys, values, and key/value mappings of a Java HashMap.

To understand this example, you should have the knowledge of the following Java programming topics:

  • Java HashMap
  • Java for-each Loop
  • Java Iterator Interface

In Java HashMap, we can iterate through its keys, values, and key/value mappings.

Java Program to Iterate over a Set

In this example, we will learn to iterate over the elements of a set in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

  • Java HashSet Class
  • Java Iterator Interface
  • Java for-each Loop