In this tutorial, we will learn how to iterate Set in Java with the help of examples. A set is a collection of unique elements or objects that are not stored in a particular order.
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 us discuss the ways of iterating a set in Java programming language.
There are mainly four 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() from Java 1.8
- With Stream API in Java 8
How to iterate a Set using Iterator in Java?
The first and most basic way of iterating a set in Java is by using an Iterator. An Iterator is an interface that provides methods to iterate over a collection of elements.
Using Iterator method, we can traverse the set only in the forward direction from the first to last element and access its elements one by one. We cannot traverse over set elements in the backward direction using the iterator() method.
Let’s take an example program in which we will iterate elements of set using the iterator() method. Follow all the steps in the coding.
Program 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. // Displaying elements of set. System.out.println("Elements in set"); System.out.println(s); // Iterating set in the forward direction. // Creating an Iterator object using iterator() method. 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 another example program where we will try to add an element during the iteration and see which exception is thrown by JVM?
Program code 2:
import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class AddDemo { public static void main(String[] args) { // Creating a set object. Set<String> set= new HashSet<>(); // Adding elements to set. set.add("Banana"); set.add("Orange"); set.add("Apple"); set.add("Mango"); // Creating an iterator object. 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 take an example where we will remove a set element at an iterator position during iteration. Look at the following code to understand better.
Program 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.
Iterating Set using Enhanced For loop
In this section, we will learn another basic way of iterating elements of set using enhanced for loop.
A for-each loop is a simplified version of a for loop that allows us to iterate over a collection of elements with no the need for an explicit Iterator. It is more concise and easier to understand than using an Iterator.
To use a for-each loop, we simply need to declare a variable to hold each element in the Set, followed by a colon and the name of the set. The for-each loop will then iterate over the set and assign each element to the variable.
Let’s take an example program where we will iterate set elements using enhanced for loop in Java.
Program 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"); // Applying enhanced for loop to iterate over set. 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
Iterating Set using forEach loop in Java 1.8?
This is the third easy way to iterate set elements in Java using for forEach() method. It is a very simple way to iterate elements. Let’s take an example program based on this method.
Program 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.
Iterating Set using Stream API in Java 1.8
The fourth way of iterating a set in Java is by using the Stream API. The Stream API is a powerful feature introduced in Java 8 that allows us to process a collection of elements in a functional and declarative way. It offers a set of operations that we can use to filter, map, and reduce a collection.
To use the Stream API, we first need to create a stream object from the set. We can create a stream object by calling the stream() method on the set.
Once we have a Stream object, we can use its forEach() method to iterate over the elements of the Set. Let’s take a simple example to iterate over set elements using Stream API.
Program code 6:
package iterateSet; import java.util.HashSet; import java.util.Set; public class IterateSetEx4 { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("apple"); set.add("banana"); set.add("orange"); set.add("mango"); set.add("grapes"); // Creating stream object by calling stream() method. set.stream().forEach(System.out::println); } }
Output: banana orange apple mango grapes
In this tutorial, we have discussed four ways to iterate over a set in Java with example programs. Iterating a set is an important operation that we do frequently in Java programming.
We have iterated over a set using Iterator, enhanced for loop, forEach() method, and Stream API. Each of these ways has its own advantages and disadvantages, and you should choose the one that best suits your of necessity.
Hope that you will have understood all the basic points of iterating set and practiced all example programs. Please, share it on social networking sites if you like this tutorial.
Thanks for reading!!!