Tutorial

Java Spliterator

Published on August 3, 2022
Default avatar

By Pankaj

Java Spliterator

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.

Java Spliterator is one of the four iterators - Enumeration, Iterator, ListIterator and Spliterator.

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. Some important points about Java Spliterator are:

  1. Java Spliterator is an interface in Java Collection API.
  2. Spliterator is introduced in Java 8 release in java.util package.
  3. It supports Parallel Programming functionality.
  4. We can use it for both Collection API and Stream API classes.
  5. It provides characteristics about Collection or API objects.
  6. We can NOT use this Iterator for Map implemented classes.
  7. It uses tryAdvance() method to iterate elements individually in multiple Threads to support Parallel Processing.
  8. It uses forEachRemaining() method to iterate elements sequentially in a single Thread.
  9. It uses trySplit() method to divide itself into Sub-Spliterators to support Parallel Processing.
  10. Spliterator supports both Sequential and Parallel processing of data.

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

Java Spliterator Class Diagram

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

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

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.

Advantages of Spliterator

  1. Unlike Iterator and ListIterator, it supports Parallel Programming functionality.
  2. Unlike Iterator and ListIterator, it supports both Sequential and Parallel Processing of data.
  3. Compare to other Iterators, it provides better performance.

Iterator vs Spliterator

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.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 18, 2018

Can you explain about Parallel Programming technically with example?

- Divakar

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 9, 2018

    Good one man. Thanks for posting.

    - Murali Mohan

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 27, 2018

      that’s too much of information to understand. thank you. very useful…!

      - bajivali shaik

        Try DigitalOcean for free

        Click below to sign up and get $200 of credit to try our products over 60 days!

        Sign up

        Join the Tech Talk
        Success! Thank you! Please check your email for further details.

        Please complete your information!

        Get our biweekly newsletter

        Sign up for Infrastructure as a Newsletter.

        Hollie's Hub for Good

        Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

        Become a contributor

        Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

        Welcome to the developer cloud

        DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

        Learn more
        DigitalOcean Cloud Control Panel