Java Program to Iterate over a Set

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Iterate through Set using the forEach loop

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


class Main {
  public static void main(String[] args) {
    // Creating an set
    Set<String> languages = new HashSet<>();
    languages.add("Java");
    languages.add("JavaScript");
    languages.add("Python");
    System.out.println("Set: " + languages);

    // Using forEach loop
    System.out.println("Iterating over Set using for-each loop:");
    for(String language : languages) {
      System.out.print(language);
      System.out.print(", ");
    }
  }
}

Output

Set: [Java, JavaScript, Python]
Iterating over Set using for-each loop:
Java, JavaScript, Python,

In the above example, we have created a set using the HashSet class. Here, we have used the for-each loop to iterate each element of the set.


Example 2: Iterate through Set using iterator()

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

class Main {
  public static void main(String[] args) {
    // Creating an Set
    Set<Integer> numbers = new HashSet<>();
    numbers.add(1);
    numbers.add(3);
    numbers.add(2);
    System.out.println("Set: " + numbers);

    // Creating an instance of Iterator
    Iterator<Integer> iterate = numbers.iterator();
    System.out.println("Iterating over Set:");
    while(iterate.hasNext()) {
      System.out.print(iterate.next() + ", ");
    }
  }
}

Output

Set: [1, 2, 3]
Iterating over Set:
1, 2, 3,

In the above example, we have used the HashSet class to create a set. We have used the iterator() method to iterate over the set. Here,

  • hasNext() - returns true if there is next element in the set
  • next() - returns the next element of the set

Example 3: Iterate through Set using forEach() method

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

class Main {
  public static void main(String[] args) {
    // create an Set
    Set<Integer> numbers = new HashSet<>();

    // add elements to the HashSet
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
    numbers.add(4);
    System.out.println("Set: " + numbers);

    // iterate each element of the set
    System.out.print("Element of Set: ");

    // access each element using forEach() method
    // pass lambda expression to forEach()
    numbers.forEach((e) -> {
      System.out.print(e + " ");
    });
  }
}

Output

Set: [1, 2, 3, 4]
Element of Set: 1 2 3 4

In the above example, we have created a set named numbers using the HashSet class. Notice the code,

numbers.forEach((e) -> {
  System.out.print(e + " ");
});

Here, we have used the forEach() method to access each element of the set. The method takes the lambda expressions as it's argument. To learn more about lamnda expression, visit Java Lambda Expressions.

Did you find this article helpful?