Different Ways to Iterate a HashSet in Java

In this post we’ll see different ways to iterate a Set or HashSet in Java. Your options to iterate a HashSet are as follows-

  1. You can use For-Each loop (Advanced or enhanced for loop), available from Java 5.
  2. You can iterate a HashSet using Iterator. Using iterator() method you can get an iterator and then using the hashNext() and next() method of the iterator you can iterate a HashSet.
  3. You can also use forEach statement available from Java 8 to loop through Set.

Example code to iterate a HashSet in Java

Here is a Java example code that shows all of the above mentioned ways to loop a Set in Java.

Output

That’s all for the topic Different Ways to Iterate a HashSet in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.