Traverse through a HashSet in Java
As we all know HashSet elements are unordered so the traversed elements can be printed in any order. In order to perform operations over our HashSet such as insertion, deletion, updating elements than first we need to reach out in order to access the HashSet. below are few ways with which we can iterate over elements to perform any kind of operations o Set elements as listed below.
- Using for-each loop
- Using forEach method
- Using Iterators
Method 1: Using for-each loop
It is another array traversing technique like for loop, while loop, do-while loop introduced in Java 5. It starts with the keyword for like a normal for-loop. Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name array traversing technique like for loop, while loop, do-while loop introduced in Java 5.
Method 2: Using forEach() method of Stream class
Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation that is, it may traverse the stream to produce a result or a side-effect.
Tip: In Java 8 or above, we can iterate a List or Collection using forEach() method.
Method 3: Using an Iterator
The iterator() method is used to get an iterator over the elements in this set. The elements are returned in no particular order. Below is the java program to demonstrate it.