VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-iterate-over-a-hashset-without-an-iterator-in-java/

⇱ How to Iterate Over a HashSet Without an Iterator in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Iterate Over a HashSet Without an Iterator in Java?

Last Updated : 1 Feb, 2024

In Java, we can iterate over a HashSet without using an Iterator. For this, we need two methods. We can directly loop through the elements of the HashSet.

In this article, we will discuss the two methods to iterate over a HashSet without using Iterator.

Program to Iterate over a HashSet without an Iterator

1. Using For-Each loop

Syntax:

for (Datatype variable : Set) { 
 //Write code using variable 
}

In this method, we will iterate over the HashSet using forEach loop. Below is the implementation:


Output
rust
python
c++
java
javascript

Explanation of the above Program:

  • In the above program, we have initialized a HashSet named set.
  • By using for-each loop we iterate over the HashSet.

2. Using forEach method

We can use forEach method which is a simple way to iterate over a set. And it can be written in single line. It is similar to ForEach loop. The values which are present in the set is stored in random order so if we iterate over it, the values will come in the random order.

Syntax:

collection.forEach(element -> {
// Write code using element
});

Below is the implementation of forEach Method:


Output
rust
python
c++
java
javascript

Explanation of the above Program:

  • In the above program, we have initialized a HashSet named set.
  • By using forEach() method, we iterate over the HashSet.
Comment