Java HashSet - spliterator() Method
The java.util.HashSet.spliterator() method is used to create a late-binding and fail-fast spliterator over the elements in the set.
Syntax
public Spliterator<E> spliterator()
Here, E is the type of element maintained by the container.
Parameters
No parameter is required.
Return Value
Returns a spliterator over the elements in the set.
Exception
NA.
Example:
In the example below, the java.util.HashSet.spliterator() method is used to create a spliterator over the elements in the given set.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a HashSet HashSet<Integer> MySet = new HashSet<Integer>(); //populating the HashSet MySet.add(10); MySet.add(20); MySet.add(30); MySet.add(40); MySet.add(50); //creating spliterator object on MySet Spliterator<Integer> splitr = MySet.spliterator(); //display content of the HashSet //using tryAdvance method System.out.print("MySet contains: "); while(splitr.tryAdvance((n) -> System.out.print(n + " "))); } }
The output of the above code will be:
MySet contains: 50 20 40 10 30
Example:
Lets consider another example to learn the concept of spliterator over the elements in the given set.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a HashSet HashSet<Integer> MySet = new HashSet<Integer>(); //populating the HashSet MySet.add(10); MySet.add(20); MySet.add(-30); MySet.add(-40); MySet.add(-50); //creating spliterator object on the HashSet Spliterator<Integer> splitr = MySet.spliterator(); //printing estimateSize of the HashSet System.out.println("Estimated size: " + splitr.estimateSize()); //display content of the HashSet using //forEachRemaining method System.out.print("MySet contains: "); splitr.forEachRemaining((n) -> System.out.print(n + " ")); } }
The output of the above code will be:
Estimated size: 5 MySet contains: -50 20 -40 10 -30
❮ Java.util - HashSet