Java HashSet iterator() Method Tutorial

In this section, we will learn what the HashSet iterator() method is and how to use it in Java.

What is Java HashSet iterator() Method?

The Java HashSet iterator() method is used to return an Iterator object from a HashSet by which we can iterate through the elements of a HashSet object.

Note: you can check the Iterator interface if you’re not familiar with this interface.

Java HashSet iterator() Method Syntax:

public Iterator<E> iterator()

iterator() Method Parameters:

The method does not take an argument.

iterator() Method Return Value:

The return value of this method is an object that implemented the Iterator interface.

iterator() Method Exceptions:

The method does not throw an exception.

Example: using HashSet iterator() method

import java.util.HashSet; 
import java.util.Iterator;
class Main{
    public static void main(String[] args) {
        HashSet<Integer> hash = new HashSet<>();
        hash.add(100);
        hash.add(200);
        hash.add(300);
        hash.add(400);
        hash.add(500);

        Iterator<Integer> iterate = hash.iterator();

        while (iterate.hasNext()){
            System.out.println(iterate.next());
        }
    }
}

Output:

400

100

500

200

300
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies