Java Program to Iterate a HashSet Collection Using the Iterator() Method

Java program to iterate a HashSet collection using the iterator() method

// Java program to iterate a HashSet collection 
// using iterator() method

import java.util.*;

public class Main {
  public static void main(String[] args) {

    HashSet < Integer > nums = new HashSet();

    nums.add(1);
    nums.add(2);
    nums.add(3);
    nums.add(4);

    System.out.println("Set items: ");
    Iterator < Integer > itr = nums.iterator();
    while (itr.hasNext()) {
      System.out.println(" " + itr.next());
    }
  }
}

Output

Set items: 
 1
 2
 3
 4
Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment