Lou*_*man 17 java java-8 spliterator
在Java 8中,提供了各种方便的实用程序来从阵列构建高效的Spliterator.但是,没有提供工厂方法来构建带有比较器的Spliterator.显然,Spliterators可以附加比较器; 他们有getComparator()方法和SORTED财产.
图书馆作者如何构建SORTEDSpliterator?
似乎没有预见到具有Spliterator除自然之外的订单这样的订单.但实施它并不难.它可能看起来像这样:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
但Java 8还没有完全修复.也许在决赛中会有一个JRE提供的解决方案.
| 归档时间: |
|
| 查看次数: |
3026 次 |
| 最近记录: |