Last Updated : 27 Nov, 2023
The spliterator() in Java Collection creates a spliterator over the elements in the collection. In simple words, it's an iterator that allows you to traverse the elements individually but is specially designed to work in parallel processing scenarios. The difference between Iterator and Spliterator is iterator does not support parallel programming but spliterator supports parallel programming.
Syntaxpublic Spliterator<E> spliterator();
Here E denotes the type of element stored inside the collection.
Return ValueIt returns a spliterator across elements in the collection.
Example 1In this example, we have used some of the methods of spliterator that we need to understand before we proceed to the example.
import java.util.List;
import java.util.ArrayList;
import java.util.Spliterator;
import java.io.*;
class GFG {
public static void main (String[] args) {
List<String> list1 = new ArrayList<String>();
list1.add("Pen");
list1.add("Paper");
list1.add("Rubber");
list1.add("Pencil");
Spliterator<String> spliterator = list1.spliterator();
System.out.println("The list contains:");
while(spliterator.tryAdvance((element)->System.out.print(element+" ")));
}
}
Output:
The list contains:Example 2
Pen Paper Rubber Pencil
In this example, we have used spliterator() in Hashset Collection.The same way as above example it traverses through the set and prints the element.
Java
import java.util.HashSet;
import java.util.Spliterator;
import java.io.*;
class GFG {
public static void main (String[] args) {
HashSet<Integer> list1 = new HashSet<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(5);
list1.add(6);
Spliterator<Integer> spliterator1 = list1.spliterator();
System.out.println("The collection contains :");
while(spliterator1.tryAdvance((element)->System.out.print(element+" ")));
}
}
Ouput:
The collection contains :
1 2 3 4 5 6
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4