spliterator 是jdk8新引入的用于并行遍历的迭代器
源码注释:
A Spliterator may also partition off some of its elements (using trySplit)) as another Spliterator, to be used in possibly-parallel operations. Operations using a Spliterator that cannot split, or does so in a highly imbalanced or inefficient manner, are unlikely to benefit from parallelism. Traversal and splitting exhaust elements; each Spliterator is useful for only a single bulk computation.
trySplit方法可以将集合分割成另一个spliterator进行并行操作
A Spliterator also reports a set of characteristics() of its structure, source, and elements from among ORDERED, DISTINCT, SORTED, SIZED, NONNULL, IMMUTABLE, CONCURRENT, and SUBSIZED. These may be employed by Spliterator clients to control, specialize or simplify computation. For example, a Spliterator for a Collection would report SIZED, a Spliterator for a Set would report DISTINCT, and a Spliterator for a SortedSet would also report SORTED. Characteristics are reported as a simple unioned bit set. Some characteristics additionally constrain method behavior; for example if ORDERED, traversal methods must conform to their documented ordering. New characteristics may be defined in the future, so implementors should not assign meanings to unlisted values.
spliterator里面有特征值如果是set实现,特征值就会标记为distinct的等等
//对任务分割,返回一个新的Spliterator迭代器 Spliterator<T> trySplit();
主要就是这个方法对实现了spliterator接口的集合进行分割后同时遍历分割后的spliterator
//用于估算还剩下多少个元素需要遍历 long estimateSize();
实际使用
arrayspliterator
代码
结果
4
6
hh1
hh3
aa2
实际使用就是使用trysplit进行多次分割后然后进行并行遍历。
具体的分割策略在对应的集合类里面有实现方法。具体遇到具体分析
tryadvance(),参数里面传入对具体某个元素的操作,返回的是当前遍历的element是否存在。
相当于interator的hasnext()和next()方法。
foreachremaining就是重复调用tryAdvance(java.util.function.Consumer <? super T>),直到它返回false。应该尽可能地覆盖它
Java 中 Iterator 和 Spliterator 的区别:
interator Spliterator
在 Java 1.2 中引入 在 Java 1.8 中引入
迭代器只单独迭代元素 Spliterator 单独和批量遍历元素
它是整个集合 API 的迭代器 它是 Collection 和Stream API 的迭代器,除了Map实现类
它使用外部迭 代 它使用内部迭代。
它是一个通用迭代器 它不是通用迭代器
不支持并行编程 它通过拆分给定的元素集来支持并行编程,以便每个集都可以单独处理。