A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/how-to-print-hashset-elements-in-java/ below:

How to Print HashSet Elements in Java?

How to Print HashSet Elements in Java?

Last Updated : 23 Jul, 2025

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.

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

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

Example:

Java
// 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>();
        hs.add(5);
        hs.add(2);
        hs.add(3);
        hs.add(6);
        hs.add(null);

        // print HashSet elements one by one.
        // Insertion 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()) {
            System.out.println(itr.next());
        }
    }
}

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.

Example:

Java
// 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
        hs.add("B");
        hs.add("C");
        hs.add("D");
        hs.add("A");
        hs.add("Z");
        hs.add("null");
        hs.add("10");

        // print HashSet
        // we don't know hash code,
        // so we don't know order
        // of insertion
        System.out.println(hs);
    }
}

Output
[A, B, C, D, null, Z, 10]


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4