How to Iterate over a HashSet in Java

Hashset:

The HashSet class implements the Set interface and is backed up by a HashMap instance that acts as a hash table. In this class, the null element is appropriate. If the Hash function correctly distributes the elements between the buckets, the class also provides continuous time for simple operations such as adding, removing, containing, and sizing.

Given a hashset , the task is to traverse the hashset in java.

Examples:

Example 1:

Input:

elements = { 1 , 2 , 3 ,1 }

Output:

1
2
3

Explanation:

Here hashset stores only unique elements that is duplicates elements are removed such as 1 in this case

Example 2:

Input:

elements = { "hello" ,"this","is", "BTechGeeeks", "Python" , "is", "BTechGeeeks","hello"}

Output:

hello
this
is
BTechGeeks
Python

Explanation:

Here hashset stores only unique elements that is duplicates elements are removed such as(hello ,is,BTechGeeks).

Traverse the HashSet in Java

With the help of iterator, we iterate HashSet. First, the iterator is used by the iterator() in Java to iterate HashSet.

// creating a hashset of type integer
HashSet<Integer> intset = new HashSet<>();
// Fetching HashSet Iterator
Iterator<String> itr = intset.iterator();

And then, using the hasNext() and Next() m├ęthodes, iterate HashSet to Java. Where the method hasNext() checks if HashSet contains elements and Next() accesses HashSet information.

Below is the implementation:

import java.io.*;
import java.lang.*;
import java.util.*;

class BtechGeeks {
    public static void main(String[] args)
        throws java.lang.Exception
    {

        // creating a hashset of type integer
        HashSet<Integer> intset = new HashSet<>();

        // add some elements of integer type to hashset
        intset.add(1);
        intset.add(2);
        intset.add(3);
        intset.add(1);

        // Fetching HashSet Iterator
        Iterator<Integer> itr = intset.iterator();

        // Loop/iterate till next element exists in HashSet
        while (itr.hasNext()) {
            // storing the next element in a integer
            // variable
            int value = itr.next();
            // printing the value
            System.out.println(value);
        }
    }
}

Output:

1
2
3

Related Programs: