How to Iterate Set in Java

In this tutorial, we will learn how to iterate Set in Java. Set interface does not provide any get() method like the List interface to retrieve elements.

Therefore, the only way to take out elements from the set can be by using Iterator() method but this method does not return elements from set in any particular order.

Let’s see how many ways to iterate set in Java.

There are mainly three ways to iterate a set in Java. We can iterate set by using any one of the following ways. They are as follows:

  • Using Iterator
  • Using Enhanced for loop
  • Using forEach()

Ways to iterate set in java

How to iterate Set using Iterator in Java?


Using Iterator method, we can traverse only in the forward direction from the first to last element. We cannot traverse over elements in the backward direction using the iterator() method.

Let’s take an example program where we will iterate elements of set using the iterator() method. Follow all the steps in the coding.


Program source code 1:

package iterateSet; 
import java.util.HashSet; 
import java.util.Iterator; 
import java.util.Set; 
public class IterateSetEx 
{ 
public static void main(String[] args) 
{ 
// Create a generic set object of type String. 
   Set<String> s = new HashSet<String>(); // s.size() is 0.
   int size = s.size(); 
  System.out.println("Size before adding elements: " +size); 

// Adding elements to set. 
   s.add("Orange"); // s.size() is 1.
   s.add("Red"); // s.size() is 2.
   s.add("Blue"); // s.size() is 3.
   s.add("Yellow"); // s.size() is 4.
   s.add("Green"); // s.size() is 5.
System.out.println("Elements in set"); 
System.out.println(s); 

Iterator<String> itr = s.iterator(); 
System.out.println("Iteration using Iterator method"); 
while(itr.hasNext())
{ 
  Object str = itr.next(); 
  System.out.println(str); 
 } 
 } 
}
Output: 
       Size before adding elements: 0 
       Elements in set 
       [Red, Blue, Yellow, Orange, Green] 
       Iteration using Iterator method 
       Red Blue Yellow Orange Green

During iteration, we cannot add an element to a set at an iterator position. If we try to add an element during iteration, JVM will throw an exception named ConcurrentModificationException.

Key point: Iteration means repeating the same operation multiple times.

Let’s take an example program where we will try to add an element during the iteration and see which exception is thrown by JVM?

Program source code 2:

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class AddDemo 
{
public static void main(String[] args) 
{
 Set<String> set= new HashSet<>();
 set.add("Banana");
 set.add("Orange");
 set.add("Apple");
 set.add("Mango");
 
 Iterator<String> itr = set.iterator();
 while(itr.hasNext()) 
 { 
   Object str = itr.next(); 
   System.out.println(str); 
   set.add("Grapes"); // Adding element during iteration. It will throw ConcurrentModificationException.
  } 
}
}
Output:
       Apple
       Exception in thread "main" java.util.ConcurrentModificationException

However, we can remove a set element at an iterator position, just as we do with the list iterator. Let’s make a program where we will remove a set element at an iterator position during iteration. Look at the following code to understand better.


Program source code 3:

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class RemoveDemo 
{
public static void main(String[] args) 
{
 Set<String> set= new HashSet<>();
 set.add("Banana");
 set.add("Orange");
 set.add("Apple");
 set.add("Mango");
 
 Iterator<String> itr = set.iterator(); 
 while(itr.hasNext()) 
 { 
   Object str = itr.next(); 
   System.out.println(str); 

// Removing Mango element. 
   if(str.equals("Mango"))
   { 
     itr.remove(); 
    } 
   } 
 System.out.println(set);
}
}
Output:
      Apple
      Mango
      Orange
      Banana
      [Apple, Orange, Banana]

Key point: List can be iterated by using the ListIterator method but Set cannot be iterated by using ListIterator.

How to iterate Set using Enhanced For loop?


In this section, we will iterate elements of set using enhanced for loop. Let’s make a program where we will iterate set elements using enhanced for loop.

Program source code 4:

package iterateSet; 
import java.util.HashSet; 
import java.util.Set; 
public class IterateSetEx2 
{ 
public static void main(String[] args) 
{ 
// Create Set object of type Integer. 
   Set<Integer> s = new HashSet<Integer>(); 
// Adding even numbers betwen 10 to 30 as elements. 
   for(int i = 10; i < = 30; i++)
   { 
     if(i % 2 == 0) 
     { 
       s.add(i); 
     } 
   } 
 System.out.println("Even numbers between 10 to 30"); 
 System.out.println(s); 
 System.out.println("Iteration Using Enchanced For Loop"); 
 for(Integer it:s)
 { 
   System.out.println(it); 
  } 
 } 
}
Output: 
       Even numbers between 10 to 30 
       [16, 18, 20, 22, 24, 10, 26, 12, 28, 14, 30] 
       Iteration Using Enhanced For Loop 
       16 18 20 22 24 10 26 12 28 14 30

Iterate Set using forEach loop in Java 1.8?


This is the third way to iterate set elements using for forEach() method. It is a very simple way to iterate elements. Let’s take an example program based on this method.
Program source code 5:
package iterateSet; 
import java.util.HashSet; 
import java.util.Set; 
public class IterateSetEx3 
{ 
public static void main(String[] args) 
{ 
 Set<Character> s = new HashSet<Character>(); 
  s.add('A'); 
  s.add('B'); 
  s.add('C'); 
  s.add('D'); 
  s.add('E'); 
 System.out.println(s); 
 
System.out.println("Iterating using forEach loop in Java 1.8"); 
 s.forEach(System.out::println); 
 } 
}
Output: 
       [A, B, C, D, E] 
       Iterating using forEach loop in Java 1.8 
       A B C D E

Key point: forEach() method is available from Java 1.8 onwards.

Hope that this tutorial has covered various types of example programs based on iterating set in Java. I hope that you will have understood this topic and enjoyed programming.
Thanks for reading!!!

Leave a Comment