Java Interface Spliterator

Spliterators can be used for traversing the elements of a source one by one. These sources could be an array, a Collection, an IO Channel or a generator function.

The main functionalities of Spliterator are-

  • Splitting the source data
  • Processing the source data

The Interface Spliterator is included in JDK 8 for taking the advantages of parallelism in addition to sequential traversal. It is designed as a parallel analogue of an iterator.

Java Interface Spliterator Declaration

Java Interface Spliterator Methods

The list of all Java Spliterator methods with some useful description are given below-

SNModifier & TypeMethodDescription
1)intcharacteristics()It is used to get a set of characteristics of this Spliterator and its elements.
2)longestimateSize()It is used to get an estimate of the number of elements remaining to iterate or returns Long.MAX_VALUE if infinite, unknown, or too expensive to compute.
3)default voidForEachRemaining(Consumer action>)It is used to performs the given action for each remaining element sequentially in the current thread until all elements have been processed or the action throws an exception.
4)default comparatorgetComaparator()It is used to get a Comparator if the given Spliterator?s source is SORTED by a Comparator.
5)default longgetExactSizeIfKnown()It is used to get an estimateSize() of the SIZED spliterator, otherwise returns -1.
6)default booleanhasCharacteristics(int characteristics)It returns true if this Spliterator's characteristics() contain all of the given characteristics.
7)booleanTryAdvance(Consumer action>)It is used to get the existing elements upon performing the specified action on it.
8)splieratortrySplit()It is used to splits the invoking spliterator if this spliterator can be partitioned, returns a reference to a new spliterator for the partition. Otherwise, it returns null.

Example 1

Output:

Estimate size: 5
Exact size: 5
Boolean Result: true
Elements of ArrayList :
101
201
301
401
501
Output from splitr2: 
101
201
Output from splitr1: 
301
401
501

Example 2

Output:

List of Fruit name-
Mango
Banana
Apple

Example 3

Output:

Python
C++
Traversing the next half of the spliterator-
Java
Android