私はこれが正しいだろうかなりわからない正直に言うと、私は、誰かが一緒に来て、これを確認しますが、ここではカスタムspliteratorを使用しての私の考えであることを願っています:
static class CustomSpl<T> extends AbstractSpliterator<T> {
private Spliterator<T> source;
private int howMany;
private int coefficient;
private Predicate<T> predicate;
private T current;
private long initialSize;
private void setT(T t) {
this.current = t;
}
public CustomSpl(Spliterator<T> source, int howMany, int coefficient, Predicate<T> predicate, long initialSize) {
super(source.estimateSize(), source.characteristics());
this.source = source;
this.howMany = howMany;
this.coefficient = coefficient;
this.predicate = predicate;
this.initialSize = initialSize;
}
@Override
public boolean tryAdvance(Consumer<? super T> action) {
boolean hasMore = source.tryAdvance(this::setT);
System.out.println(current);
if (!hasMore) {
return false;
}
if (predicate.test(current)) {
++howMany;
}
if (initialSize - howMany <= coefficient) {
return false;
}
action.accept(current);
return true;
}
}
とのために我々は係数5
有するだけケアに言っための例では、これは、唯一の4つの要素を生成する:
Spliterator<Integer> sp = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).stream().spliterator();
long count = StreamSupport.stream(new CustomSpl<>(sp, 0, 5, x -> x > 3, sp.getExactSizeIfKnown()), false)
.count();
をまたこれは、既知のサイズのspliteratorsことが可能です。
なぜforループを使用しないのでしょうか? Java 9は、必要な処理を行うStream :: takeWhileメソッドを提供します。 – daniu
半分+ 1が真であればtrueを返し、半分+ 1が偽の場合はfalseを返しますか? – ByeBye
@ByeBye半分より大きい場合は正確なカウントを返したいが、カウントが半分よりも小さい場合は何か他のものを返す –