Skip to content
Related Articles

Related Articles

How to Print HashSet Elements in Java?

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 15 Dec, 2020

In HashSet, duplicates are not allowed. If we are trying to insert duplicates then we won’t get any compile-time or runtime error and the add() method simply returns false.

We can use 2 ways to print HashSet elements:

  1. Using the iterator() method to traverse the set elements and printing it.
  2. Directly printing it using a reference variable.

Method 1: By using Cursor which is Iterator.

  • If we want to get objects one by one from the collection then we should go for the cursor.
  • We can apply the Iterator concept for any Collection Object and hence it is a Universal Cursor.
  • By using Iterator we can perform both read and remove operations.
  • We can create an Iterator object by using the iterator method of Collection Interface.

public Iterator iterator();   //  Iterator method of Collection Interface.

  • Creating an iterator object

Iterator itr = c.iterator();  // where c is any Collection Object like ArrayList,HashSet etc.



// Java program to print the elements
// of HashSet using iterator cursor
import java.util.*;
class GFG {
    public static void main(String[] args)
        HashSet<Integer> hs = new HashSet<Integer>();
        // print HashSet elements one by one.
        // Inserton order in not preserved and it is based
        // on hash code of objects.
        // creates Iterator oblect.
        Iterator itr = hs.iterator();
        // check element is present or not. if not loop will
        // break.
        while (itr.hasNext()) {

Method 2: We can directly print HashSet elements by using the HashSet object reference variable. It will print the complete HashSet object.

Note: If we do not know the hash code, so you can’t decide the order of insertion.



// Java program to directly print the
// elements of HashSet
import java.util.*;
class GFG {
    public static void main(String[] args)
        // create HashSet object
        HashSet<String> hs = new HashSet<String>();
        // add element in HashSet object
        // print HashSet
        // we dont't know hash code,
        // so we don't know order
        // of insertion
[A, B, C, D, null, Z, 10]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!