This post will discuss various methods to iterate over set in Java.

1. Using Iterator

We can use iterator() that returns an iterator to iterate over a set, as shown below:

Download  Run Code

 
Please note that the iterator will throw a ConcurrentModificationException if the set is modified after it is created except through the iterator’s own remove method.

2. Using enhanced for-loop

As Set implements the Iterable interface, we can use enhanced for-loop to loop through the set, as shown below:

Download  Run Code

3. Java 8 – Converting set to stream

In Java 8 and above, we can loop over a set with the help of streams, lambdas, and forEach, as shown below:

Download  Run Code

4. Converting set to array

We can first convert the set into an array using toArray() method and then print it using Arrays.toString() method. There are many implementations of toArray() method, as shown below:

Download Code

5. Converting set to vector

The Enumeration interface provides methods to enumerate through the elements of a Vector. So, we can convert the set into a vector and finally print all elements of that vector.

Download  Run Code

6. Converting set to string

If we’re only required to display the contents of the set, we can simply print the string representation of the set using the toString() method, as shown below:

Download  Run Code

That’s all about iterating over a Set in Java.

 
Related Posts:

Iterate Map in Java using keySet() method

Iterate Map in Java using the entrySet() method