Iterate over a Set in Java

In this post, we 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:

Java

Download   Run Code

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

2. Using enhanced for loop:

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

Java

Download   Run Code

3. Java 8 – Converting Set to Streams

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

Java

Download   Run Code

4. Converting Set to Array

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

Java

Download   Run Code

5. Converting Set to Vector

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.

Java

Download   Run Code

6. Converting Set to String

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

Java

Download   Run Code

 
Related Posts:

5 ways to Iterate Map using keySet() in Java

5 ways to Iterate Map in Java using entrySet()

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of