March 7, 2022

How to Iterate a Java HashSet

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 hasNext() 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.

Java HashSet iteration example

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

public class SetIteration {
  public static void main(String[] args) {
    Set<String> capitalSet = new HashSet<String>();
    // adding elements
    capitalSet.add("New Delhi");
    capitalSet.add("Lisbon");
    capitalSet.add("Buenos Aires");
    capitalSet.add("Beijing");
        
    System.out.println("**Iterating HashSet using For-Each loop**");
    for(String capital : capitalSet){
      System.out.println("Capital city- " + capital);
    }
        
    System.out.println("**Iterating using Iterator**");

    Iterator<String> itr = capitalSet.iterator();
    while(itr.hasNext()){            
      System.out.println("Capital city- " + itr.next());        
    }
        
    System.out.println("**Iterating using forEach statement**");

    capitalSet.forEach((c)->System.out.println("Capital city- " + c));

    System.out.println("**Iterating using forEach statement (Method reference)**");
    // Using forEach with method reference
    capitalSet.forEach(System.out::println);        
  }
}
Output
**Iterating HashSet using For-Each loop**
Capital city- Beijing
Capital city- New Delhi
Capital city- Lisbon
Capital city- Buenos Aires
**Iterating using Iterator**
Capital city- Beijing
Capital city- New Delhi
Capital city- Lisbon
Capital city- Buenos Aires
**Iterating using forEach statement**
Capital city- Beijing
Capital city- New Delhi
Capital city- Lisbon
Capital city- Buenos Aires
**Iterating using forEach statement (Method reference)**
Beijing
New Delhi
Lisbon
Buenos Aires

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


You may also like

No comments:

Post a Comment