从数组中创建高效的Java 8排序Spliterator [英] Making an efficient Java 8 sorted Spliterator from an array
问题描述
在Java 8中,各种方便的实用工具用于从数组构建高效的Spliterator。但是,没有提供工厂方法来构建带有比较器的Spliterator。显然,Spliterators可以附加比较器;他们有 getComparator()
方法和 SORTED
属性。
In Java 8, a variety of convenient utilities are provided to build efficient Spliterators from arrays. However, no factory methods are provided there to build a Spliterator with a comparator. Clearly Spliterators are allowed to have attached comparators; they have a getComparator()
method and a SORTED
property.
图书馆作者如何构建 SORTED
Spliterators?
How are library authors supposed to build SORTED
Spliterators?
推荐答案
似乎没有预见到这样的 Spliterator
,订单不是自然的。但实施它并不难。它可能如下所示:
It seems that it is not foreseen to have such a Spliterator
with an order other than natural. But implementing it is not that hard. It could look like this:
class MyArraySpliterator implements Spliterator.OfInt {
final int[] intArray;
int pos;
final int end;
final Comparator<? super Integer> comp;
MyArraySpliterator(int[] array, Comparator<? super Integer> c) {
this(array, 0, array.length, c);
}
MyArraySpliterator(int[] array, int s, int e, Comparator<? super Integer> c) {
intArray=array;
pos=s;
end=e;
comp=c;
}
@Override
public OfInt trySplit() {
if(end-pos<64) return null;
int mid=(pos+end)>>>1;
return new MyArraySpliterator(intArray, pos, pos=mid, comp);
}
@Override
public boolean tryAdvance(IntConsumer action) {
Objects.requireNonNull(action);
if(pos<end) {
action.accept(intArray[pos++]);
return true;
}
return false;
}
@Override
public boolean tryAdvance(Consumer<? super Integer> action) {
Objects.requireNonNull(action);
if(pos<end) {
action.accept(intArray[pos++]);
return true;
}
return false;
}
@Override
public long estimateSize() {
return end-pos;
}
@Override
public int characteristics() {
return SIZED|SUBSIZED|SORTED|ORDERED|NONNULL;
}
@Override
public Comparator<? super Integer> getComparator() {
return comp;
}
}
但Java 8尚未完全修复。也许在决赛中会有一个JRE提供的解决方案。
But Java 8 is not entirely fixed yet. Maybe there will be a JRE-provided solution in the final.
这篇关于从数组中创建高效的Java 8排序Spliterator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!