How to use Spliterator in Java 8 - Example Tutorial

Hello friends, we are here today again on the journey of Java. And today, we are gonna learn about SplitIterator class from Stream package that may not be used in your day-to-day life but can be very useful to know as Java internally does use this with both normal streams and parallel streamsAs always, let’s take an example of a situation. I will present you with a situation and you guys can think about it. So, let’s say we have an array with 50k records in it. Now, these all records need to be modified, let’s say they are strings and we need to append the string with a name. Now, traversing the array sequentially would be time-consuming. Any innovative ideas my friends?

Yes! If you are thinking of leveraging parallel programming/concurrency you are right on spot. But wait, we have heard of using different threads for different tasks but how will we keep a track of what thread will handle what records? How will we traverse? But worry not friends as we have Spliterator to save us from this hassle!

So what’s the wait? Let’s understand what it is.

1. What is Spliterator in Java? 

The Java Spliterator interface is a built-in iterator that divides a stream into smaller chunks. The processing of these smaller pieces can be done simultaneously leveraging concurrency.

We may never encounter a situation to use Spliterator directly in real-world programming. It will operate precisely like a Java Iterator in regular operations.

The streams and parallel streams in Java use Spliterator internally which is efficient for concurrency.

For understanding Spliterator, we need to look at all the methods Spliterator provides, and then we will use them in our code. So let’s see what methods are provided by Splitertaor and what functions do they perform.

2. Spliterator methods:

Here are important methods of SplitIterator in Java and when to use them:

int characteristics() - returns an Integer representing characteristics of spliterator and its elements. It can be ORDERED, SORTED, DISTINCT, SIZED, NONNULL, IMMUTABLE, CONCURRENT, SUBSIZED.

long estimateSize() - it returns the estimated size of left to traverse. It is ‘estimated’ because it will return Long.MAX_VALUE if size (number of elements left to traverse) is unknown, infinite, or computationally too expensive to calculate.

default long getExactSizeIfKnown() - it returns the spliterator size if it has ‘SIZED’ property, else returns ‘-1’;

default comparator getComparator() - this method returns null if spliterator’s source is sorted in the natural order, if the source is SORTED by a comparator, returns that comparator and throws an illegalStateException if the source is not sorted.

How to use  Spliterator in Java 8 - Example Tutorial

default boolean hasCharacteristics(int characteristic) - returns true if the characteristic passed is possessed by the spliterator.

boolean tryAdvance(Consumer action) - If the next element exists, performs the given action on it and returns true, else if the element is not present, returns false.

Default void forEachRemaining(Consumer action) - executes the provided action for each remaining element until all items have been processed or the action produces an exception. This is done sequentially on a single thread.

Spliterator trySplit() - this method splits the current spliterator’s elements into two parts if possible and assigns them to a new spliterator. The current spliterator will iterate over one portion and the new iterator will iterate over the other portion.

Now, after understanding all the methods, let’s see how we can use some of them in our code.

3. Spliterator code Example

Here is a Java program to demonstrate how to use Spliterator in Java:

import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;

public class SpliteratorExample {

public static void main(String[] args) {
List<String> list = new ArrayList<>();

Spliterator<String> spliterator = list.spliterator();

//check characteristics of spliterator
System.out.println("characteristics : "+spliterator.characteristics());

//check the hasCharacteristics function
System.out.println("has characteristics : " + spliterator.hasCharacteristics(Spliterator.ORDERED));

//check the estimateSize function
System.out.println("estimateSize : "+spliterator.estimateSize());

//check the exact size if known
System.out.println("getExactSizeIfKnown : "+spliterator.getExactSizeIfKnown());

System.out.println("spliterator for each remaining");
//forEachRemaining function

System.out.println("trying split");
//trySplit method

spliterator = list.spliterator();
Spliterator<String> spliterator_new = spliterator.trySplit();

System.out.println("current spliterator done!");
System.out.println("new spliterator done!");

//tryAdvance function




How to use  Spliterator in Java 8 - Example Tutorial

Now, as we have understood what Spliterator is and how it is used. I guess you guys would be confident enough to try, test, and get hands-on for spliterator. But, before that, please keep these below important points in mind.

Important points of Spliterator in Java

  • Java Spliterator is a Java Collection API interface.
  • Spliterator is a new feature in Java 8's java.util package.
  • It has Parallel Programming capabilities.
  • Both Collection API and Stream API classes can benefit from it.
  • It contains information about the Collection of API objects.
  • This Iterator cannot be used with Map supported classes.
  • It supports Parallel Processing by using the tryAdvance() function to iterate items separately in multiple Threads.
  • It iterates items sequentially in a single thread using the forEachRemaining() function.
  • To allow Parallel Processing, it divides itself into Sub-Spliterators using the trySplit() function.
  • Spliterator is capable of both sequential and parallel processing.

Always remember, 

That's all about what is Spliterator in Java 8. This is a great utility class to process a big stream into smaller junk concurrently. Spliterator allows you to break your Stream into smaller parts and then process them simultaneously. You can use this utility class to speed up some lengthy CPU-intensive operations in Java. 

See you guys in the next article. Till then, peace :p

Other Java 8 Tutorials and Examples you may like:

  • How to read a file in just one line in Java 8? (solution)
  • 10 JDK 7 features to revise before starting with Java 8? (features)
  • Java 8 map + filter + collect tutorial (examples)
  • Top 10 Java 8 Tutorials for Programmers (read here)
  • 5 good books to learn Java 8 from scratch (see here)
  • 20 Examples of new Date and Time API of JDK 8 (examples)
  • 5 Free Courses to learn Java 8 and Java 9 (courses)
  • 7 Best Cousess to learn Java Collections and Stream (courses)
  • The Complete Java Developer RoadMap (guide)
  • 10 Examples of Stream in Java 8 (Examples)
  • 10 Examples of Collectors in Java 8 (examples)
  • 10 Courses to become a full-stack Java developer (free courses)

P. S. -  If you want to learn more about new features in Java 8 then please see this list of best Java 8 courses on Udemy. It explains all important features of Java 8 like lambda expressions, streams, functional interfaces, Optional, new date, and time API, and other miscellaneous changes

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.