Java HashSet.spliterator() – Examples

In this tutorial, we will learn about the Java HashSet.spliterator() method, and learn how to use this method to get a Spliterator object for the elements of this HashSet, with the help of examples.

spliterator()

HashSet.spliterator() creates a late-binding and fail-fast Spliterator over the elements in this HashSet.

ADVERTISEMENT

Syntax

The syntax of spliterator() method is

HashSet.spliterator()

Returns

The method returns Spliterator<E> object where E is the type of object in HashSet.

Example 1 – spliterator()

In this example, we will define and initialize a HashSet of Strings. We shall then get Spliterator for this HashSet using spliterator() method, and iterate over the elements of Spliterator object.

Java Program

import java.util.HashSet;
import java.util.Spliterator;

public class Example {  
	public static void main(String[] args) {
		HashSet<String> hashSet = new HashSet<String>();
		hashSet.add("a");
		hashSet.add("b");
		hashSet.add("c");
		hashSet.add("d");

		Spliterator<String> split = hashSet.spliterator(); 
		split.forEachRemaining( 
				(obj) -> System.out.println(obj));
	}  
}

Output

a
b
c
d

Example 2 – spliterator()

In this example, we will define and initialize a HashSet of Integers. We shall then get Spliterator for this HashSet using spliterator() method, and iterate over the elements of Spliterator object.

Java Program

import java.util.HashSet;
import java.util.Spliterator;

public class Example {  
	public static void main(String[] args) {
		HashSet<Integer> hashSet = new HashSet<Integer>();
		hashSet.add(7);
		hashSet.add(2);
		hashSet.add(9);
		hashSet.add(1);

		Spliterator<Integer> split = hashSet.spliterator(); 
		split.forEachRemaining( 
				(obj) -> System.out.println(obj));
	}  
}

Output

1
2
7
9

Conclusion

In this Java Tutorial, we have learnt the syntax of Java HashSet.spliterator() method, and also learnt how to use this method with the help of Java examples.