The Wayback Machine - https://web.archive.org/web/20241002111149/https://www.geeksforgeeks.org/how-to-iterate-hashset-in-java/
Open In App

How to Iterate HashSet in Java?

Last Updated : 17 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. It stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.

Methods to Iterate HashSet

There are three simple ways to iterate over a HashSet, which is the following :

  1. Using Iterator
  2. Without using Iterator (using for loop)
  3. Using for-each loop

Method 1: Iterator method

In this method, we iterate HashSet with the help of iterator. First, we make an iterator to iterate HashSet with the help of the iterator() method in Java.

// Create a iterator of integer type to iterate HashSet

Iterator<Integer> it = set.iterator();

And then iterate HashSet with the help of hasNext() and Next() method in Java. Where hasNext() method check whether HashSet has elements or not and, Next() method access the data of HashSet.

Note: Use Next() method only one time after hasNext().

Example:

Java
// Java program to iterate the HashSet
// using iterator

import java.util.*;

class GFG {
    public static void main(String[] args)
    {
        // Creating a new HashSet for iteration
        HashSet<Integer> set = new HashSet<>();

        // Add data to HashMap
        set.add(10);
        set.add(20);

        // Duplicates not allowed in HashSet, so avoid by
        // HashSet
        set.add(10);
        set.add(50);

        // Duplicates not allowed in HashSet, so avoid by
        // HashSet
        set.add(50);

        // Create a iterator of type integer to iterate
        // HashSet
        Iterator<Integer> it = set.iterator();

        System.out.println(
            "Iterate HashSet using iterator : ");

        // Iterate HashSet with the help of hasNext() and
        // next() method
        while (it.hasNext()) {

            // Print HashSet values
            System.out.print(it.next() + " ");
        }
    }
}

Output
Iterate HashSet using iterator : 
50 20 10 

Method 2: Iterate using for loop

In this method, we iterate HashSet using a simple for loop. Below is the implementation of this approach:

Example:

Java
// Java program to iterate the HashSet
// using for loop

import java.util.*;

class GFG {
    public static void main(String[] args)
    {
        // Creating a new HashSet for iteration
        HashSet<String> set = new HashSet<>();

        // Add data to HashSet
        set.add("Hello");
        set.add("geeks");
        set.add("on");

        //  duplicates not allowed in HashSet, so avoid by
        //  HashSet
        set.add("geeks");
        set.add("for");

        //  duplicates not allowed in HashSet, so avoid by
        //  HashSet
        set.add("geeks");

        System.out.println(
            "Iterate HashSet using for loop : ");

        // Iterate throw a simple for loop
        for (String ele : set) {
            // Print HashSet data
            System.out.print(ele + " ");
        }
    }
}

Output
Iterate HashSet using for loop : 
Hello geeks for on 

Method 3: Using forEach() method

In this method, we iterate HashSet using forEach() loop in Java. Below is the implementation of this method:

Example:

Java
// Java program to iterate using forEach() loop

import java.util.*;

class GFG {
    public static void main(String[] args)
    {
        // Creating a new HashSet for iteration
        HashSet<String> set = new HashSet<>();

        // Add data to HashSet
        set.add("Hello");
        set.add("geeks");
        set.add("on");

        //  duplicates not allowed in HashSet, so avoid by
        //  HashSet
        set.add("geeks");
        set.add("for");

        //  duplicates not allowed in HashSet, so avoid by
        //  HashSet
        set.add("geeks");

        System.out.println(
            "Iterate HashSet using forEach loop : ");

        // Iterate throw a forEach method in Java
        set.forEach(System.out::println);
    }
}

Output
Iterate HashSet using forEach loop : 
Hello
geeks
for
on


Similar Reads

How to Copy or Append HashSet to Another HashSet in Java?
HashSet is used to store distinct values in Java. HashSet stores the elements in random order, so there is no guarantee of the elements' order. The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. We can copy or append a HashSet to another HashSet. There is a couple of ways to copy HashSet or
4 min read
How to Iterate Over a HashSet Without an Iterator in Java?
In Java, we can iterate over a HashSet without using an Iterator. For this, we need two methods. We can directly loop through the elements of the HashSet. In this article, we will discuss the two methods to iterate over a HashSet without using Iterator. Program to Iterate over a HashSet without an Iterator1. Using For-Each loopSyntax: for (Datatype
2 min read
HashSet contains() Method in Java
The Java.util.HashSet.contains() method is used to check whether a specific element is present in the HashSet or not. So basically it is used to check if a Set contains any particular element. Syntax: Hash_Set.contains(Object element) Parameters: The parameter element is of the type of HashSet. This is the element that needs to be tested if it is p
2 min read
HashSet clear() Method in Java
The Java.util.HashSet.clear() method is used to remove all the elements from a HashSet. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing HashSet. Syntax: Hash_Set.clear() Parameters: The method does not take any parameter R
1 min read
Convert HashSet to a ArrayList in Java
ArrayList class is a resizable array, present in java.util package. The difference between an array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an ArrayList with
4 min read
How to Find the Minimum and Maximum Value from Java HashSet?
HashSet is used to store distinct values in Java. The HashSet does not guarantee the constant order of elements over time, which means when we iterate a HashSet, there is no guarantee that we get the same order of elements as we added in order. HashSet does not provide any built-in method to get the maximum and minimum values. There are a couple of
3 min read
HashSet isEmpty() Method in Java
The Java.util.HashSet.isEmpty() method is used to check if a HashSet is empty or not. It returns True if the HashSet is empty otherwise it returns False. Syntax: Hash_Set.isEmpty() Parameters: This method does not take any parameter Return Value: The function returns True if the set is empty else returns False. Below program illustrate the Java.uti
1 min read
HashSet iterator() Method in Java
The Java.util.HashSet.iterator() method is used to return an iterator of the same elements as the hash set. The elements are returned in random order from what present in the hash set. Syntax: Iterator iterate_value = Hash_Set.iterator(); Parameters: The function does not take any parameter. Return Value: The method iterates over the elements of th
1 min read
HashSet remove() Method in Java
HashSet remove() method is used to remove a particular element from a HashSet. Note that it is only after JDK version 1.2 and ahead, and will throw compilation errors before in version JDK 1 and JDK1.1. Note: This method returns true if the specified element is present in the HashSet otherwise it returns boolean false. Syntax: HashSet.remove(Object
2 min read
HashSet size() Method in Java
The Java.util.HashSet.size() method is used to get the size of the HashSet or the number of elements present in the HashSet. Syntax: Hash_Set.size() Parameters: This method does not takes any parameter. Return Value: The method returns the size or the number of elements present in the HashSet. Below program illustrate the Java.util.HashSet.size() m
1 min read
HashSet add() Method in Java
The Java.util.HashSet.add() method in Java HashSet is used to add a specific element into a HashSet. This method will add the element only if the specified element is not present in the HashSet else the function will return False if the element is already present in the HashSet. Syntax: Hash_Set.add(Object element) Parameters: The parameter element
1 min read
HashSet clone() Method in Java
The Java.util.HashSet.clone() method is used to return a shallow copy of the mentioned hash set. It just creates a copy of the set. Syntax: Hash_Set.clone() Parameters: The method does not take any parameters. Return Value: The method just returns a copy of the HashSet. Below program illustrate the Java.util.HashSet.clone() method: // Java code to
1 min read
Traverse through a HashSet in Java
As we all know HashSet elements are unordered so the traversed elements can be printed in any order. In order to perform operations over our HashSet such as insertion, deletion, updating elements than first we need to reach out in order to access the HashSet. below are few ways with which we can iterate over elements to perform any kind of operatio
3 min read
HashSet spliterator() method in Java
The spliterator() method of HashSet returns a Spliterator with the same elements as HashSet. The returned Spliterator is late-binding and fail-fast Spliterator. A late-binding Spliterator binds to the source of elements means HashSet at the point of first traversal, first split, or first query for estimated size, rather than at the time the Spliter
2 min read
How to sort HashSet in Java
Given a HashSet in Java, the task is to sort this HashSet. Examples: Input: HashSet: [Geeks, For, ForGeeks, GeeksforGeeks] Output: [For, ForGeeks, Geeks, GeeksforGeeks] Input: HashSet: [2, 5, 3, 1, 4] Output: [1, 2, 3, 4, 5] The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is
2 min read
Difference between ArrayList and HashSet in Java
Here are couple of differences between ArrayList and HashSet. Inheritance: Implementation: Implementation : ArrayList implements List interface while HashSet implements Set interface in Java.Internal implementation: ArrayList is backed by an Array while HashSet is backed by an HashMap.Duplicates : ArrayList allows duplicate values while HashSet doe
3 min read
HashSet hashCode() method in Java with Example
The hashCode() method of HashSet in Java is used to get the hashCode value for this instance of the HashSet. It returns an integer value which is the hashCode value for this instance of the HashSet. Syntax: public int hashCode() Parameters: This function has no parameters. Returns: The method returns an integer value which is the hashCode value for
2 min read
HashSet containsAll() method in Java with Example
The containsAll() method of Java HashSet is used to check whether two sets contain the same elements or not. It takes one set as a parameter and returns True if all of the elements of this set is present in the other set. Syntax: public boolean containsAll(Collection C) Parameters: The parameter C is a Collection. This parameter refers to the set w
2 min read
HashSet removeAll() method in Java with Example
The removeAll() method of java.util.HashSet class is used to remove from this set all of its elements that are contained in the specified collection.Syntax: public boolean removeAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be removed from this set.Returns Value: This method returns true if this
3 min read
HashSet toArray() method in Java with Example
The toArray() method of Java HashSet is used to form an array of the same elements as that of the HashSet. Basically, it copies all the element from a HashSet to a new array. Syntax: Object[] arr = HashSet.toArray() Parameters: The method does not take any parameters. Return Value: The method returns an array containing the elements similar to the
2 min read
HashSet toArray(T[]) method in Java with Example
The toArray(T[]) method method of HashSet class in Java is used to form an array of the same elements as that of the HashSet. It returns an array containing all of the elements in this HashSet in the correct order; the run-time type of the returned array is that of the specified array. If the HashSet fits in the specified array, it is returned ther
4 min read
HashSet equals() method in Java with Example
The equals() method of java.util.HashSet class is used verify the equality of an Object with a HashSet and compare them. The list returns true only if both HashSet contains same elements, irrespective of order. Syntax: public boolean equals(Object o) Parameters: This method takes the object o as a parameter to be compared for equality with this set
2 min read
HashSet retainAll() method in Java with Example
The retainAll() method of java.util.HashSet class is used to retain from this set all of its elements that are contained in the specified collection. Syntax: public boolean retainAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be retained from this set. Returns Value: This method returns true if th
3 min read
Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java
In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHashSet, and TreeSet in java. Differences Between Ha
6 min read
Convert HashSet to TreeSet in Java
Hashset: Hashset in Java is generally used for operations like search, insert and delete. It takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table. TreeSet: TreeSet in Java takes O(log n) for search, insert and delete which is higher than HashSet. But TreeSet keeps sorted data
3 min read
Check whether array has all identical elements using Arrays.asList() and HashSet in Java
Given an array arr[] of N elements, the task is to check whether the array have all same (identical) elements or not without using the loop. If all elements are same then print Yes otherwise print No. Examples: Input: arr[] = {2, 2, 2, 2, 2} Output: Yes The given array has all identical elements i.e. 2. Input: arr[] = {2, 3, 3, 3, 3, 2, 2} Output:
2 min read
How to Get Random Elements from Java HashSet?
Unlike List classes, the HashSet class does not provide any methods using which we can get the elements using their index. It makes it difficult to get random elements from it using the index. We need to get random elements from HashSet, which can be done by either of the two ways: By converting it to an arrayUsing an Iterator or a for loop Example
3 min read
Convert HashSet to array in Java
Java HashSet class is used to create a collection that uses a hash table for the storage of elements. It inherits AbstractSet class and implements Set Interface. The key points about HashSet are: HashSet contains unique elements only.HashSet allows null values.The insertion of elements in a HashSet is based on a hashcode.HashSet is best used for se
2 min read
How to Print HashSet Elements in Java?
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: Using the iterator() method to traverse the set elements and printing it.Directly printing it using a reference variable. Method 1:
2 min read
How to Convert Comma Separated String to HashSet in Java?
Given a Set of String, the task is to convert the Set to a comma-separated String in Java. Examples: Input: Set<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"] Output: "Geeks, For, Geeks" Input: Set<String> = ["G", "e", "e", "k", "s"] Output: "G, e, e, k, s" There are two ways in which we can convert comma separated string to Java Hash
2 min read
Practice Tags :