Java Program to Iterate over a Set

Updated on December 6, 2024
Iterate over a set header image

Introduction

Java Collections Framework includes the Set interface, which is a collection that cannot contain duplicate elements. It's widely used in Java programming when you want to store unique items. Iterating over the elements of a Set is a common task that enables developers to access and manipulate the elements effectively.

In this article, you will learn how to iterate over a Set in Java using various methods. Explore examples demonstrating iteration with an enhanced for loop, an iterator, and Java 8 stream API.

Iterating Using Enhanced For Loop

Simple For-Each Loop

  1. Initialize a Set with some elements.

  2. Use an enhanced for loop to iterate through the Set.

    java
    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            Set<Integer> numbers = new HashSet<>();
            numbers.add(1);
            numbers.add(2);
            numbers.add(3);
    
            for (int num : numbers) {
                System.out.println(num);
            }
        }
    }
    

    This code snippet creates a HashSet and adds three integers to it. It then uses a for-each loop, a common approach to iterate over a Set because of its concise syntax and direct access to elements.

Iterating Using Iterator

Standard Iterator

  1. Create a Set and populate it.

  2. Retrieve an iterator from the Set.

  3. Use while loop to iterate using the Iterator.

    java
    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            Set<String> fruits = new HashSet<>();
            fruits.add("Apple");
            fruits.add("Banana");
            fruits.add("Cherry");
    
            Iterator<String> iterator = fruits.iterator();
            while (iterator.hasNext()) {
                String fruit = iterator.next();
                System.out.println(fruit);
            }
        }
    }
    

    By using an Iterator, you gain more control over the iteration process, such as the ability to remove elements during iteration which is not possible directly with a for-each loop.

Using Java 8 Stream APIs

Stream.forEach Method

  1. Initialize your Set.

  2. Use Java 8 Stream API to iterate through the Set.

    java
    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            Set<Double> values = new HashSet<>(Arrays.asList(1.1, 2.2, 3.3));
            values.stream().forEach(System.out::println);
        }
    }
    

    This example uses the stream() method to create a stream of elements from the Set. The forEach method of the stream is utilized to perform an action for each element, which here is printing the element to the console.

Conclusion

Iterating over a Set in Java can be effectively managed using various techniques depending on the requirements of your application. The enhanced for loop offers simplicity and clarity for most straightforward use cases. Meanwhile, using an Iterator provides additional capabilities like element removal during iteration. For functional-style programming or complex operations, the Java 8 Stream API is highly beneficial. By mastering these methods, you ensure efficient manipulation and traversal of Set collections in your Java applications.