HashSet iterator() in Java

iterator(): This method is available in java.util.HashSet class of Java.

Syntax:

Iterator<K > java.util.HashSet.iterator()

This method returns an iterator over the elements in this set. The elements are returned in no particular order.

Parameters: NA

Returns: an Iterator over the elements in this set.

Exceptions: NA

Approach

Java

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

public class HashSetiterator {
    public static void main(String[] args) {

        HashSet<String> hashSet = new HashSet<String>();

        hashSet.add("Hello");
        hashSet.add("Java");
        hashSet.add("C++");
        hashSet.add("Hello");

        Iterator<String> iterator = hashSet.iterator();

        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }

    }
}

Output:

Java C++ Hello 

No comments:

Post a Comment