...

/

HashSet: Iteration and Sorting

HashSet: Iteration and Sorting

Let's look at different ways to iterate a HashSet.

Iterating a HashSet

Below are the different methods to iterate over a HashSet.

Using for loop

A HashSet can be easily iterated using an enhanced for loop as shown below.

Press + to interact
import java.util.HashSet;
import java.util.Set;
public class HashSetDemo {
public static void main(String args[]) {
Set<Integer> set = new HashSet<>();
set.add(23);
set.add(34);
set.add(56);
for(int i : set) {
System.out.println(i);
}
}
}
...