In Java, the Set interface or HashSet class does not offer a get() method for retrieving elements. The only way to extract elements from a Set is by iterating over it using the Iterator or traversing it using the advanced for loop (for each loop). More specifically, you can invoke the iterator() method of the Set interface to get the iterator and then traverse it using a loop. The iterator() retrieves an iterator over the elements in the sets (but it retrieves them in no particular order).
This write will discuss several examples of using the iterator() method in Java.
How to Use the Set iterator() Method in Java
The iterator() is a built-in method of set interface that loops through a set and retrieves the iterator/values. Moreover, it doesn’t accept any parameter and is used with the dot syntax:
setName.iterator();
The retrieved iterator elements will be in a random order.
Now let’s learn how to create a set, add some elements, and iterate over it using the iterator() method.
Example: Iterating a Set/HashSet Using Iterator
First import the required interfaces and classes like “Set”, “HashSet”, and “Iterator” from the “java.util” package:
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class SetIterator {
public static void main(String args[]) {
Set<Integer> empIds = new HashSet<Integer>();
empIds.add(4);
empIds.add(2);
empIds.add(3);
empIds.add(1);
empIds.add(6);
empIds.add(7);
empIds.add(9);
empIds.add(8);
empIds.add(10);
empIds.add(5);
System.out.println("The Given Set is ==> " + empIds);
Iterator<Integer> iterateSet = empIds.iterator();
System.out.println("The Retrieved Iterator is ==> ");
while (iterateSet.hasNext()) {
System.out.println(iterateSet.next());
}
}
}
In the above code,
- First, we create a HashSet of integers named “empIds” and initialize it using the add() method.
- Next, we get/create an iterator using the “iterator()” method.
- Finally, we use the while loop with the “hasNext()” and “Next()” methods to traverse/iterate over the set:
Important: you can use the forEachRemaining() on the obtained iterator (instead of while loop) to get the elements of the targeted set. Here is a practical example:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class SetIterator {
public static void main(String args[]) {
Set<String> writerNames = new HashSet<>(Arrays.asList("Anees", "Asghar", "Joseph", "Henry","Matt","Alex","Tim","Joe","Dean","Jones"));
System.out.println("The Given Set is ==> " + writerNames);
Iterator<String> iterateSet = writerNames.iterator();
System.out.println("The Retrieved Iterator is ==> ");
iterateSet.forEachRemaining(System.out::println);
}
}
This time, we create a set of strings named “writerNames” and initialize it with the list of names using Arrays.asList(). After this, we use the iterator() method to get the iterator for the given set. Finally, we use the forEachRemaining() method to print the obtained/retrieved iterator elements:
Useful Alternatives of Set iterator() Method in Java
The below table depicts some handy alternatives(along with syntax and description) of Java’s set iterator() method:
Method | Description | Syntax |
for-each Loop | Enhanced for loop or for-each loop is one of the most convenient ways of iterating over a collection, like a set. | for (type varName: set) { //code statements;} |
forEach() Method | Java 8 and later versions have a forEach() method that lets you iterate/traverse each element of a collection, like set. | setName.forEach(varName -> { //code statements}); |
Stream API | You can use the stream API to convert the set to a stream and then forEach() method to iterate over it. | setName.stream().forEach(varName -> { // code statements}); |
Alternative 1: For Each Loop
In the following example, we use the for-each loop to achieve the same functionality as the set iterator():
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class SetIterator {
public static void main(String args[]) {
Set<String> writerNames = new HashSet<>
(Arrays.asList("Anees", "Asghar", "Joseph", "Henry","Matt","Alex","Tim","Joe","Dean","Jones"));
System.out.println("The Given Set is ==> " + writerNames);
System.out.println("The Retrieved Iterator is ==> ");
for (String iterate: writerNames)
{
System.out.println(iterate);
}
}
}
In this code we use the enhanced for-each loop to traverse and print each element of the given set:
Alternative 2: forEach() Method
Now let’s see how you can loop through a set using the forEach() method:
import java.util.*;
public class SetIterator {
public static void main(String args[]) {
Set<Integer> empIds = new HashSet<Integer>();
empIds.add(4);
empIds.add(2);
empIds.add(6);
empIds.add(7);
empIds.add(9);
System.out.println("The Given Set is ==> " + empIds);
System.out.println("The Retrieved Iterator is ==> ");
empIds.forEach(iterate ->
{
System.out.println(iterate);
});
}
}
We invoke the forEach() method on the empIds set to iterate and print each element of the given set:
Alternative 3: Stream API
In the following code, first, we convert the set elements into a stream using stream(). After this, we use the forEach() method of stream API to traverse each set element:
import java.util.*;
public class SetIterator {
public static void main(String args[]) {
Set<Integer> empIds = new HashSet<Integer>();
empIds.add(14);
empIds.add(112);
empIds.add(126);
empIds.add(107);
empIds.add(109);
System.out.println("The Given Set is ==> " + empIds);
System.out.println("The Retrieved Iterator is ==> ");
empIds.stream().forEach(System.out::println);
}
}
The output snippet indicates that each element of the given set is successfully iterated and printed:
That’s all about iterating a set using the set iterator() method in Java.
Conclusion
In Java, iterator() is an in-built method of the set interface that loops through a set and retrieves the iterator/values. The retrieved elements are randomly sorted. Moreover, this method doesn’t accept any parameter and is used with the dot syntax as “setName.iterator();”. The iterator() method is used with a while loop along with hasNext() and next() methods to traverse a retrieved iterator. Also, you can use the forEachRemaining() method to traverse the obtained/retrieved iterator. This post has provided an in-depth insight into how to use the iterator() method in Java.