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

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()

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

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.