Java Spliterator

Like Iterator and ListIterator, Spliterator is a Java Iterator, which is used to iterate elements one-by-one from a List implemented object.

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).

Main Functionalities of Spliterator

  • Splitting the source data.
  • Processing the source data.

Java Spliterator Class Diagram

The following diagram shows the Class Diagram of Java Spliterator interface. It has many fields and methods.

Java Spliterator Methods

In this section, we will list out all Java Spliterator methods one by one with some useful description.

  1. int characteristics(): Returns a set of characteristics of this Spliterator and its elements.
  2. long estimateSize(): Returns an estimate of the number of elements that would be encountered by a forEachRemaining() traversal, or returns Long.MAX_VALUE if infinite, unknown, or too expensive to compute.
  3. default void forEachRemaining(Consumer action): 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 Comparator getComparator(): If this Spliterator’s source is SORTED by a Comparator, returns that Comparator.
  5. default long getExactSizeIfKnown(): Convenience method that returns estimateSize() if this Spliterator is SIZED, else -1.
  6. default boolean hasCharacteristics(int characteristics): Returns true if this Spliterator’s characteristics() contain all of the given characteristics.
  7. boolean tryAdvance(Consumer action): If a remaining element exists, performs the given action on it, returning true; else returns false.
  8. Spliterator trySplit(): If this spliterator can be partitioned, returns a Spliterator covering elements, that will, upon return from this method, not be covered by this Spliterator.

Java Spliterator Example

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

journaldev is optimized for learning.© journaldev .
All Right Reserved and you agree to have read and accepted our term and condition