Search code examples
javadata-structuresiteratorjava-8spliterator

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?


Solution

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