| by Arround The Web | No comments

How to Iterate over a Set in a Java Program?

Iteration over a set allows developers to process each unique element individually without any duplicates. It also eliminates the need for manual index management or complex looping constructs. It helps in performing data processing or analysis tasks, eliminating duplicate elements, implementing business logic in an application, or generating lists based on the unique elements present in the set.

This article demonstrates the methods that can be used to iterate over a set in a Java program.

How to Iterate Over a Set in a Java Program?

The set offers developers the opportunity to utilize standard iteration mechanisms like, Iterator interface,  for-each loop and forEachRemaining() method. Visit the below methods description along with codec examples to understand the process of iterating over a set in Java:

Method 1: Using Iterator Interface

Iterator interface provides a way to iterate over the elements in a set sequentially. It allows the programmer to safely remove elements while iterating, avoiding concurrent modification exceptions:

Follow the below code for a better understanding:

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

class HelloWorld {
 public static void main(String[] args)  // creation of main() method
 {
  Set<String> testSet = new HashSet<>();
  testSet.add("John Wick");
  testSet.add("Sisu");
  testSet.add("Avenger");
  Iterator<String> itratr = testSet.iterator();
   while (itratr.hasNext()) {
   String ele = itratr.next();
   System.out.println(ele);
  }
 }
}

 
Explanation of the above code:

    • First, declare a set named “testSet” of type “String” and initialize it as a “HashSet”.
    • Next, insert multiple data elements by utilizing the “add()” method, and create an instance of “Iterator
    • Then, utilize the “while()” loop to iterate over the elements of the “testSet”.
    • After that, retrieves the next element from the set using the “hasNext()” method of the iterator. It assigns the element to the “ele” variable of type String.
    • In the end, display the “ele” variable on the console.

After the end of the execution phase:


The output shows that the iteration over a set has been done using the Iterator interface.

Method 2: Using Enhanced “for” Loop

Using the “for-each loop”, the iteration process automatically handles the iterator internally. It offers a concise and readable syntax for iterating over a set and hides the complexities of managing an iterator.

Visit the below code for better explanation:

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

class HelloWorld {
 public static void main(String[] args)  // creation of main() method
 {
  Set<String> testSet= new HashSet<>();
  testSet.add("John Wick");
  testSet.add("Sisu");
  testSet.add("Avenger");
   for (String elem : set) {
    System.out.println(elem);
   }
 }
}

 
Explanation of the above code:

    • First, the “Set” is created with the name “testSet” and elements are added to the set using the “add()” method.
    • Next, the enhanced “for” loop is utilized that internally iterates over the “testSet” and displays each containing element on the console.

After the end of the compilation:


The snapshot confirms the interaction over the set using an enhanced “for” loop.

Method 3: Using the “forEachRemaining()” Method

The “forEachRemaining()” method is an alternative to the traditional while loop and iterator combination for iterating over a collection. It avoids the need for explicit iterator initialization and termination, making the code more concise.

Visit the below code for a better understanding:

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

class HelloWorld {
 public static void main(String[] args)  // creation of main() method
 {
  Set<String> testSet= new HashSet<>();
  testSet.add("John Wick");
  testSet.add("Sisu");
  testSet.add("Avenger");
  Iterator<String> iterator = testSet.iterator();
  iterator.forEachRemaining(element -> System.out.println(element));
 }
}

 
In the above code block:

    • First, the “Set” is declared named “testSet” and the dummy data is inserted in it.
    • Next, the instance of the “Iterator” class is created, and the “forEachRemaining()” method is used.
    • This method iterates over the data element of the set and prints each element on the console.

After the end of execution:


The snapshot shows the iteration over a set has been done to print elements on the console.

Conclusion

In Java, the iteration can be done using the “Iterator” interface, enhanced “for” loop, and by utilizing the “forEachRemaining()” method. Iteration over a set offers benefits such as easy access to unique elements, simplicity, flexibility, and compatibility with standard iteration interfaces. Moreover, by doing this the programmer can process each residing element individually. That is all about the procedure to iterate over a set in Java.

Share Button

Source: linuxhint.com

Leave a Reply