What is the HashSet.spliterator() method in Java?

In this shot, we will learn how to use the HashSet.spliterator() method in Java.

The HashSet.spliterator() method is present in the HashSet class inside the java.util package.

The HashSet.spliterator() method returns a Spliterator with the same elements as the HashSet in an unordered format. The returned Spliterator is a late-binding and fail-fast Spliterator. A late-binding Spliterator binds to the source of elements, which means that the HashSet is at the point of first traversal, first split, or first query for estimated size, rather than at the time the Spliterator is created.

Parameters

HashSet.spliterator() doesn’t accept any parameters.

Return value

The HashSet.spliterator() method returns spliterators over HashSet elements.

Code

Let’s have a look at the code.

import java.io.*;
import java.util.*;
class Main
{
public static void main(String args[])
{
HashSet<Integer> hash_set1 = new HashSet<Integer>();
hash_set1.add(1);
hash_set1.add(8);
hash_set1.add(5);
hash_set1.add(3);
hash_set1.add(0);
Spliterator<Integer> num = hash_set1.spliterator();
System.out.println("The spliterator values are: ");
num.forEachRemaining((n) -> System.out.println(n));
}
}

Explanation

  • In lines 1 and 2, we import the required packages and classes.

  • In line 4, we make a Main class.

  • In line 6, we make a main() function.

  • In line 8, we declare a HashSet of Integer type, i.e., hash_set1.

  • From lines 9 to 13, we use the HashSet.add() method to add the elements into the HashSet.

  • In line 15, we make an object of the Spliterator class to use the HashSet.spliterator() method.

  • In line 16, we display a message for the upcoming spliterator values.

  • In line 17, we display the spliterators with the forEachRemaining() function, which sequentially displays each remaining element in the current thread until all elements have been processed or the action throws an exception.

Free Resources