Search⌘ K

HashSet: Iteration and Sorting

Explore different ways to iterate over a HashSet in Java, including enhanced for loops, iterators, and the forEach method. Understand how to sort HashSet elements by converting them to other collections like ArrayList. This lesson enables you to manage and organize HashSet data effectively.

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.

Java
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);
}
}
}

Using

...