简体   繁体   中英

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

Java 8中Spliterator类的用例场景是什么?

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.

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);
}

Spliterator is an extension of the timeless Iterator class that allows for splitting of a stream of objects to iterate over ( Stream works by collecting the operations before iterating).

I cannot think of any times when the average developer would have to work with Spliterator . The Collection and Collections APIs are incredibly rich in Java 8, and in most cases you'd be better off using a vanilla Collection subclass instead of building your own Stream interface.

An example of when you might want to use Spliterator might be a library for graphs using a linked data structure over which the standard Spliterator / stream() is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM