Write a Java Program to Iterate over a Set

Iterating over a set is a common task in Java programming.

A set is an unordered collection of objects that does not allow duplicate values.

Java provides several ways to iterate over a set.

In this tutorial, we will discuss some of the most common ways to iterate over a set in Java.


Using a for-each loop

The simplest way to iterate over a set is to use a for-each loop.

A for-each loop is a shorthand notation for iterating over a collection.

It iterates over each element in the collection and executes the loop body for each element.

Set<String> set = new HashSet<>(); set.add("apple"); set.add("banana"); set.add("orange");
  for (String s : set) { System.out.println(s); }

This code snippet creates a HashSet of strings and adds three strings to the set.

Then, it iterates over the set using a for-each loop and prints each element to the console.

Using an iterator

Another way to iterate over a set is to use an iterator.

An iterator is an object that provides a way to access the elements in a collection one by one.

The iterator() method of the Set interface returns an iterator object that can be used to iterate over the set.

Set<String> set = new HashSet<>(); set.add("apple"); set.add("banana"); set.add("orange");
  Iterator<String> iterator = set.iterator(); while (iterator.hasNext()) { String s = iterator.next(); System.out.println(s); }

This code snippet creates a HashSet of strings and adds three strings to the set.

Then, it creates an iterator object by calling the iterator() method on the set.

It uses a while loop and the hasNext() method of the iterator to check if there are more elements in the set.

If there are more elements, it retrieves the next element using the next() method and prints it to the console.

Using a forEach() method

Java 8 introduced a new method called forEach() for iterating over collections.

This method takes a lambda expression as a parameter and applies the lambda expression to each element in the collection.

Set<String> set = new HashSet<>(); set.add("apple"); set.add("banana"); set.add("orange");
  set.forEach(s -> System.out.println(s));

This code snippet creates a HashSet of strings and adds three strings to the set.

Then, it uses the forEach() method to iterate over the set and print each element to the console.

The lambda expression s -> System.out.println(s) is passed as a parameter to the forEach() method.

The lambda expression takes a string parameter s and prints it to the console.


Conclusion

Iterating over a set in Java is a common task that can be accomplished using several methods.

The for-each loop, iterator, and forEach() method are some of the most common ways to iterate over a set.

Each method has its advantages and disadvantages, and the choice of method depends on the specific use case.