Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be a good use-case scenario for the Spliterator in Java 8?

What would be a good use-case scenario for the Spliterator class in Java 8?

like image 934
jrobertsz66 Avatar asked Jul 09 '14 18:07

jrobertsz66


People also ask

What is the use of Spliterator in Java?

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 Spliterator is an interface in Java Collection API.

What is the difference between iterator and Spliterator?

An Iterator is a simple representation of a series of elements that can be iterated over. A Spliterator can be used to split given element set into multiple sets so that we can perform some kind of operations/calculations on each set in different threads independently, possibly taking advantage of parallelism.

What are the significant advantages of Java 8?

Figure 1.1. Programming languages ecosystem and climate change. The main benefit of Java 8 to a programmer is that it provides more programming tools and concepts to solve new or existing programming problems more quickly or, more importantly, in a more concise, more easily maintainable way.

What is stream Spliterator?

Spliterator is an internal iterator that breaks the stream into the smaller parts. These smaller parts can be processed in parallel.


2 Answers

Normally, an application developer would not consume the Spliterator API directly. But if you are providing an API, and implement your own collection-like class, you can implement Spliterator to adapt your collection to the Stream API. This supports a functional approach, parallel processing, and other features.

For example, I wrote a utility to enumerate IP addresses in a network, specified by CIDR notation. It's not really a collection; that is, it doesn't carry list of all of the addresses in memory at once, only the network number and netmask. But by exposing a Spliterator, it can be easily adapted to a Stream. (Each Spliterator just tracks the current IP address and maximum address in its share of the network.)

Another example from the core Java runtime is DirectoryStream for traversing the file system.

like image 64
erickson Avatar answered Oct 16 '22 05:10

erickson


Use case example: "Converts iterator to stream"

public static <T> Stream<T> iteratorToFiniteStream(final Iterator<T> iterator) {
   final Iterable<T> iterable = () -> iterator;
  return StreamSupport.stream(iterable.spliterator(), false);
}
like image 26
Karol Król Avatar answered Oct 16 '22 06:10

Karol Król