Java Spliterator is one of the four iterators - Enumeration, Iterator, ListIterator and Spliterator.
Like Iterator and ListIterator, Spliterator is a Java Iterator, which is used to iterate elements one-by-one from a List implemented object. Some important points about Java Spliterator are:
java.util
package.tryAdvance()
method to iterate elements individually in multiple Threads to support Parallel Processing.forEachRemaining()
method to iterate elements sequentially in a single Thread.trySplit()
method to divide itself into Sub-Spliterators to support Parallel Processing.Spliterator itself does not provide the parallel programming behavior. However, it provides some methods to support it. Developers should utilize Spliterator interface methods and implement parallel programming by using Fork/Join Framework (one good approach).
The following diagram shows the Class Diagram of Java Spliterator interface. It has many fields and methods.
In this section, we will list out all Java Spliterator methods one by one with some useful description.
In this section, we will discuss about how to create Java Spliterator object using spliterator() and will develop simple example.
import java.util.Spliterator;
import java.util.ArrayList;
import java.util.List;
public class SpliteratorSequentialIteration
{
public static void main(String[] args)
{
List<String> names = new ArrayList<>();
names.add("Rams");
names.add("Posa");
names.add("Chinni");
// Getting Spliterator
Spliterator<String> namesSpliterator = names.spliterator();
// Traversing elements
namesSpliterator.forEachRemaining(System.out::println);
}
}
Output:-
Rams
Posa
Chinni
If we observe the above program and output, we can easily understand that this Spliterator.forEachRemaining() method works in the same way as ArrayList.foreach(). Yes, both works in similar way.
Iterator | Spliterator |
---|---|
Introduced in Java 1.2. | Introduced in Java 1.8. |
It is an Iterator for whole Collection API. | It is an Iterator for both Collection and Stream API, except Map implemented classes. |
It is an Universal Iterator. | It is NOT an Universal Iterator. |
It does NOT support Parallel Programming. | It supports Parallel Programming. |
That’s all about Spliterator in Java. Reference: API Doc
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Can you explain about Parallel Programming technically with example?
- Divakar
Good one man. Thanks for posting.
- Murali Mohan
that’s too much of information to understand. thank you. very useful…!
- bajivali shaik