[英]What would be a good use-case scenario for the Spliterator in Java 8?
Normally, an application developer would not consume the Spliterator
API directly. 通常,应用程序开发人员不会直接使用
Spliterator
API。 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. 但是,如果您要提供API并实现自己的类似集合的类,则可以实现
Spliterator
以使您的集合适应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. 例如,我编写了一个实用程序来枚举网络中的IP地址,由CIDR表示法指定。 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
. 但是通过暴露
Spliterator
,它可以很容易地适应Stream
。 (Each Spliterator
just tracks the current IP address and maximum address in its share of the network.) (每个
Spliterator
只跟踪其网络共享中的当前IP地址和最大地址。)
Another example from the core Java runtime is DirectoryStream
for traversing the file system. 核心Java运行时的另一个示例是用于遍历文件系统的
DirectoryStream
。
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). Spliterator
是永恒Iterator
类的扩展,它允许分割对象流以进行迭代( Stream
通过在迭代之前收集操作来工作)。
I cannot think of any times when the average developer would have to work with Spliterator
. 我无法想到普通开发人员何时必须使用
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. Collection
和Collections
API在Java 8中非常丰富,在大多数情况下,您最好使用vanilla Collection
子类而不是构建自己的Stream
接口。
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. 您可能希望使用
Spliterator
可能是使用链接数据结构的图形库,标准Spliterator
/ stream()
未定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.