beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to Iterate over a Set/HashSet

By Chaitanya Singh | Filed Under: Java.util package

There are following two ways to iterate through HashSet:
1) Using Iterator
2) Without using Iterator

Example 1: Using Iterator

import java.util.HashSet;
import java.util.Iterator;

class IterateHashSet{ 
  public static void main(String[] args) {
     // Create a HashSet
     HashSet<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("Chaitanya");
     hset.add("Rahul");
     hset.add("Tim");
     hset.add("Rick");
     hset.add("Harry");
 
     Iterator<String> it = hset.iterator();
     while(it.hasNext()){
        System.out.println(it.next());
     }
  }
}

Output:

Chaitanya
Rick
Harry
Rahul
Tim

Example 2: Iterate without using Iterator

import java.util.HashSet;
import java.util.Set;

class IterateHashSet{ 
  public static void main(String[] args) {
     // Create a HashSet
     Set<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("Chaitanya");
     hset.add("Rahul");
     hset.add("Tim");
     hset.add("Rick");
     hset.add("Harry");
 
     for (String temp : hset) {
        System.out.println(temp);
     }
  }
}

Output:

Chaitanya
Rick
Harry
Rahul
Tim

Comments

  1. Witty says

    October 23, 2015 at 8:18 PM

    Hello!
    Can I ask you a question?
    Is there any difference in declarations in 1st and 2nd examples:
    HashSet hset = new HashSet(); and
    Set hset = new HashSet();

    Reply
    • Taiwo Azeez A says

      March 29, 2016 at 5:51 PM

      Technically, yes, for the 1st line, you are coding to an implementation while for the 2nd line, you are coding to an interface. In otherwords, hashset is a concrete class while the Seet is an interface

      Reply
      • tedd says

        January 6, 2017 at 1:38 AM

        It is always a good idea to put the interface name on the left side from good software engineering practices. It hides implementation details.

        Reply

Leave a Reply Cancel reply

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

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap