目录
1、map / flatMap / mapToObj / mapToLong / mapToDouble /asLongStream / asDoubleStream
2、limit / skip
3、sorted
4、distinct / boxed
5、findFirst / findAny
6、anyMatch / allMatch / noneMatch
7、iterator / spliterator
8、close / onClose
本篇博客继续上一篇《Java8 Stream API 之 IntPipeline(一) 源码解析》讲解IntStream其他方法的实现细节。
这几个都是map类方法,都是将流中的元素做适当处理,返回一个新值或者新的流,实现基本一致,如下:
@Override
public final IntStream map(IntUnaryOperator mapper) {
Objects.requireNonNull(mapper);
return new StatelessOp(this, StreamShape.INT_VALUE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedInt(sink) {
@Override
public void accept(int t) {
//将applyAsInt的执行结果传递给下一个流处理动作
downstream.accept(mapper.applyAsInt(t));
}
};
}
};
}
@Override
public final IntStream flatMap(IntFunction extends IntStream> mapper) {
return new StatelessOp(this, StreamShape.INT_VALUE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedInt(sink) {
@Override
public void begin(long size) {
downstream.begin(-1);
}
@Override
public void accept(int t) {
//flatMap的入参mapper的返回值是一个IntStream
try (IntStream result = mapper.apply(t)) {
if (result != null)
//如果mapper返回的IntStream流非空,则遍历其中的所有元素,传递给下一个流处理动作
result.sequential().forEach(i -> downstream.accept(i));
}
}
};
}
};
}
@Override
public final Stream mapToObj(IntFunction extends U> mapper) {
Objects.requireNonNull(mapper);
return new ReferencePipeline.StatelessOp(this, StreamShape.INT_VALUE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedInt(sink) {
@Override
public void accept(int t) {
//apply方法将t转换成对象
downstream.accept(mapper.apply(t));
}
};
}
};
}
@Override
public final LongStream mapToLong(IntToLongFunction mapper) {
Objects.requireNonNull(mapper);
return new LongPipeline.StatelessOp(this, StreamShape.INT_VALUE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedInt(sink) {
@Override
public void accept(int t) {
//apply方法将t转换成Long
downstream.accept(mapper.applyAsLong(t));
}
};
}
};
}
@Override
public final DoubleStream mapToDouble(IntToDoubleFunction mapper) {
Objects.requireNonNull(mapper);
return new DoublePipeline.StatelessOp(this, StreamShape.INT_VALUE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedInt(sink) {
@Override
public void accept(int t) {
//apply方法将t转换成Double
downstream.accept(mapper.applyAsDouble(t));
}
};
}
};
}
@Override
public final LongStream asLongStream() {
return new LongPipeline.StatelessOp(this, StreamShape.INT_VALUE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedInt(sink) {
@Override
public void accept(int t) {
downstream.accept((long) t);
}
};
}
};
}
@Override
public final DoubleStream asDoubleStream() {
return new DoublePipeline.StatelessOp(this, StreamShape.INT_VALUE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedInt(sink) {
@Override
public void accept(int t) {
downstream.accept((double) t);
}
};
}
};
}
limit用于限制流中元素的最大个数,skip用于跳过指定个数的元素,其实现如下:
@Override
public final IntStream skip(long n) {
if (n < 0)
throw new IllegalArgumentException(Long.toString(n));
if (n == 0) //不需要跳过
return this;
else
//第一个参数表示跳过的元素个数,第二个参数表示允许的元素最大个数,-1表示无限制
return SliceOps.makeInt(this, n, -1);
}
@Override
public final IntStream limit(long maxSize) {
if (maxSize < 0)
throw new IllegalArgumentException(Long.toString(maxSize));
return SliceOps.makeInt(this, 0, maxSize);
}
//SliceOps的实现
public static IntStream makeInt(AbstractPipeline, Integer, ?> upstream,
long skip, long limit) {
if (skip < 0)
throw new IllegalArgumentException("Skip must be non-negative: " + skip);
return new IntPipeline.StatefulOp(upstream, StreamShape.INT_VALUE,
flags(limit)) {
//unorderedSkipLimitSpliterator给下面两个方法使用的
Spliterator.OfInt unorderedSkipLimitSpliterator(
Spliterator.OfInt s, long skip, long limit, long sizeIfKnown) {
if (skip <= sizeIfKnown) {
// Use just the limit if the number of elements
// to skip is <= the known pipeline size
limit = limit >= 0 ? Math.min(limit, sizeIfKnown - skip) : sizeIfKnown - skip;
skip = 0;
}
return new StreamSpliterators.UnorderedSliceSpliterator.OfInt(s, skip, limit);
}
@Override
Spliterator opEvaluateParallelLazy(PipelineHelper helper,
Spliterator spliterator) {
long size = helper.exactOutputSizeIfKnown(spliterator);
if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
return new StreamSpliterators.SliceSpliterator.OfInt(
(Spliterator.OfInt) helper.wrapSpliterator(spliterator),
skip,
calcSliceFence(skip, limit));
} else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
return unorderedSkipLimitSpliterator(
(Spliterator.OfInt) helper.wrapSpliterator(spliterator),
skip, limit, size);
}
else {
return new SliceTask<>(this, helper, spliterator, Integer[]::new, skip, limit).
invoke().spliterator();
}
}
@Override
Node opEvaluateParallel(PipelineHelper helper,
Spliterator spliterator,
IntFunction generator) {
long size = helper.exactOutputSizeIfKnown(spliterator);
if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
// Because the pipeline is SIZED the slice spliterator
// can be created from the source, this requires matching
// to shape of the source, and is potentially more efficient
// than creating the slice spliterator from the pipeline
// wrapping spliterator
Spliterator s = sliceSpliterator(helper.getSourceShape(), spliterator, skip, limit);
return Nodes.collectInt(helper, s, true);
} else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
Spliterator.OfInt s = unorderedSkipLimitSpliterator(
(Spliterator.OfInt) helper.wrapSpliterator(spliterator),
skip, limit, size);
// Collect using this pipeline, which is empty and therefore
// can be used with the pipeline wrapping spliterator
// Note that we cannot create a slice spliterator from
// the source spliterator if the pipeline is not SIZED
return Nodes.collectInt(this, s, true);
}
else {
return new SliceTask<>(this, helper, spliterator, generator, skip, limit).
invoke();
}
}
@Override
//实现skip和limit的核心方法
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedInt(sink) {
long n = skip;
long m = limit >= 0 ? limit : Long.MAX_VALUE;
@Override
public void begin(long size) {
//计算遍历的元素个数
downstream.begin(calcSize(size, skip, m));
}
@Override
public void accept(int t) {
if (n == 0) {
//n等于0表示已经跳过指定个数的元素了
if (m > 0) {
m--;
downstream.accept(t);
}
//m小于等于0表示已经达到最大元素个数限制了
}
else {
n--;
}
}
@Override
public boolean cancellationRequested() {
//m等于0了需要终止遍历
return m == 0 || downstream.cancellationRequested();
}
};
}
};
}
abstract static class StatefulOp extends IntPipeline {
StatefulOp(AbstractPipeline, E_IN, ?> upstream,
StreamShape inputShape,
int opFlags) {
super(upstream, opFlags);
//校验两者流元素的类型是否一致
assert upstream.getOutputShape() == inputShape;
}
@Override
final boolean opIsStateful() {
return true; //StatelessOp此方法返回false
}
@Override
//此方法是父类AbstractPipeline定义的方法,默认实现是抛出UnsupportedOperationException异常
//StatefulOp的子类必须重写此方法
abstract Node opEvaluateParallel(PipelineHelper helper,
Spliterator spliterator,
IntFunction generator);
}
private static long calcSize(long size, long skip, long limit) {
return size >= 0 ? Math.max(-1, Math.min(size - skip, limit)) : -1;
}
其中opEvaluateParallelLazy和opEvaluateParallel都是AbstractPipeline定义的方法,其默认实现如下:
Node opEvaluateParallel(PipelineHelper helper,
Spliterator spliterator,
IntFunction generator) {
throw new UnsupportedOperationException("Parallel evaluation is not supported");
}
@SuppressWarnings("unchecked")
Spliterator opEvaluateParallelLazy(PipelineHelper helper,
Spliterator spliterator) {
return opEvaluateParallel(helper, spliterator, i -> (E_OUT[]) new Object[i]).spliterator();
}
这两方法都是返回在并行环境下使用的线程安全的经过包装的Spliterator和Node实现,其调用链如下:
因为涉及的类和并发处理比较复杂,此处就深究了。
sorted用于对流中的元素排序,其实现如下:
@Override
public final IntStream sorted() {
return SortedOps.makeInt(this);
}
static IntStream makeInt(AbstractPipeline, Integer, ?> upstream) {
return new OfInt(upstream);
}
private static final class OfInt extends IntPipeline.StatefulOp {
OfInt(AbstractPipeline, Integer, ?> upstream) {
super(upstream, StreamShape.INT_VALUE,
StreamOpFlag.IS_ORDERED | StreamOpFlag.IS_SORTED);
}
@Override
//flags是前一个流处理动作的combinedFlags,sink表示前一个流处理动作
public Sink opWrapSink(int flags, Sink sink) {
Objects.requireNonNull(sink);
//如果已经排序了,则直接返回
if (StreamOpFlag.SORTED.isKnown(flags))
return sink;
else if (StreamOpFlag.SIZED.isKnown(flags))
//如果限定了元素个数
return new SizedIntSortingSink(sink);
else
//如果元素个数未知
return new IntSortingSink(sink);
}
@Override
public Node opEvaluateParallel(PipelineHelper helper,
Spliterator spliterator,
IntFunction generator) {
if (StreamOpFlag.SORTED.isKnown(helper.getStreamAndOpFlags())) {
//如果已排序好
return helper.evaluate(spliterator, false, generator);
}
else {
Node.OfInt n = (Node.OfInt) helper.evaluate(spliterator, true, generator);
int[] content = n.asPrimitiveArray();
//执行并行排序
Arrays.parallelSort(content);
//返回排序好的结果
return Nodes.node(content);
}
}
}
private static abstract class AbstractIntSortingSink extends Sink.ChainedInt {
protected boolean cancellationWasRequested;
AbstractIntSortingSink(Sink super Integer> downstream) {
super(downstream);
}
@Override
public final boolean cancellationRequested() {
//父类实现是调用downstream的cancellationWasRequested方法,此处没有调用
cancellationWasRequested = true;
return false;
}
}
private static final class SizedIntSortingSink extends AbstractIntSortingSink {
private int[] array;
private int offset;
SizedIntSortingSink(Sink super Integer> downstream) {
super(downstream);
}
@Override
public void begin(long size) {
//size为流中元素的个数
if (size >= Nodes.MAX_ARRAY_SIZE)
throw new IllegalArgumentException(Nodes.BAD_SIZE);
array = new int[(int) size];
}
@Override
public void end() {
//当所有流元素都通过accept方法传递完成会调用end方法
//对流中元素做排序处理
Arrays.sort(array, 0, offset);
//通知下一个流处理动作开始处理
downstream.begin(offset);
if (!cancellationWasRequested) {
//如果没有请求终止当前流处理
for (int i = 0; i < offset; i++)
//将数组中的流处理动作传递给下一个流
downstream.accept(array[i]);
}
else {
//如果下一个流处理动作也终止了则停止处理流元素
for (int i = 0; i < offset && !downstream.cancellationRequested(); i++)
downstream.accept(array[i]);
}
//通知下一个流处理动作处理结束
downstream.end();
array = null;
}
@Override
public void accept(int t) {
//上一个流处理动作通过此方法将硫元素传递给当前Sink,注意此时并不会继续向下传递,而是放在array中保存起来了
array[offset++] = t;
}
}
private static final class IntSortingSink extends AbstractIntSortingSink {
//SpinedBuffer的实现跟ArrayList类似,相当于一个会自动扩容的数组
private SpinedBuffer.OfInt b;
IntSortingSink(Sink super Integer> sink) {
super(sink);
}
@Override
public void begin(long size) {
if (size >= Nodes.MAX_ARRAY_SIZE)
throw new IllegalArgumentException(Nodes.BAD_SIZE);
//初始化b
b = (size > 0) ? new SpinedBuffer.OfInt((int) size) : new SpinedBuffer.OfInt();
}
@Override
public void end() {
int[] ints = b.asPrimitiveArray();
//执行排序
Arrays.sort(ints);
//通知流处理开始
downstream.begin(ints.length);
//同上,将数组中排序好的流处理元素传递给下一个流
if (!cancellationWasRequested) {
for (int anInt : ints)
downstream.accept(anInt);
}
else {
for (int anInt : ints) {
if (downstream.cancellationRequested()) break;
downstream.accept(anInt);
}
}
//通知流处理结束
downstream.end();
}
@Override
public void accept(int t) {
//保存上一个流处理动作传递过来的元素
b.accept(t);
}
}
@Override
public final IntStream distinct() {
//很低效的实现,实际是借助了对象流的distinct实现
return boxed().distinct().mapToInt(i -> i);
}
@Override
public final Stream boxed() {
//转换成对象流
return mapToObj(Integer::valueOf);
}
//ReferencePipeline就是对象流的Stream接口实现
@Override
public final Stream distinct() {
return DistinctOps.makeRef(this);
}
//DistinctOps的实现
static ReferencePipeline makeRef(AbstractPipeline, T, ?> upstream) {
return new ReferencePipeline.StatefulOp(upstream, StreamShape.REFERENCE,
StreamOpFlag.IS_DISTINCT | StreamOpFlag.NOT_SIZED) {
Node reduce(PipelineHelper helper, Spliterator spliterator) {
// If the stream is SORTED then it should also be ORDERED so the following will also
// preserve the sort order
TerminalOp> reduceOp
= ReduceOps.>makeRef(LinkedHashSet::new, LinkedHashSet::add,
LinkedHashSet::addAll);
return Nodes.node(reduceOp.evaluateParallel(helper, spliterator));
}
@Override
Node opEvaluateParallel(PipelineHelper helper,
Spliterator spliterator,
IntFunction generator) {
if (StreamOpFlag.DISTINCT.isKnown(helper.getStreamAndOpFlags())) {
// No-op
return helper.evaluate(spliterator, false, generator);
}
else if (StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
return reduce(helper, spliterator);
}
else {
// Holder of null state since ConcurrentHashMap does not support null values
AtomicBoolean seenNull = new AtomicBoolean(false);
ConcurrentHashMap map = new ConcurrentHashMap<>();
TerminalOp forEachOp = ForEachOps.makeRef(t -> {
if (t == null)
seenNull.set(true);
else
map.putIfAbsent(t, Boolean.TRUE);
}, false);
forEachOp.evaluateParallel(helper, spliterator);
// If null has been seen then copy the key set into a HashSet that supports null values
// and add null
Set keys = map.keySet();
if (seenNull.get()) {
// TODO Implement a more efficient set-union view, rather than copying
keys = new HashSet<>(keys);
keys.add(null);
}
return Nodes.node(keys);
}
}
@Override
Spliterator opEvaluateParallelLazy(PipelineHelper helper, Spliterator spliterator) {
if (StreamOpFlag.DISTINCT.isKnown(helper.getStreamAndOpFlags())) {
// No-op
return helper.wrapSpliterator(spliterator);
}
else if (StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
// Not lazy, barrier required to preserve order
return reduce(helper, spliterator).spliterator();
}
else {
// Lazy
return new StreamSpliterators.DistinctSpliterator<>(helper.wrapSpliterator(spliterator));
}
}
@Override
Sink opWrapSink(int flags, Sink sink) {
Objects.requireNonNull(sink);
if (StreamOpFlag.DISTINCT.isKnown(flags)) {
//之前的流处理动作已经去重过了,则直接返回
return sink;
} else if (StreamOpFlag.SORTED.isKnown(flags)) {
//如果是一个已经排序好的流
return new Sink.ChainedReference(sink) {
boolean seenNull;
T lastSeen;
@Override
public void begin(long size) {
seenNull = false;
lastSeen = null;
downstream.begin(-1);
}
@Override
public void end() {
seenNull = false;
lastSeen = null;
downstream.end();
}
@Override
public void accept(T t) {
if (t == null) {
if (!seenNull) { //如果没有遇到过null
seenNull = true;
downstream.accept(lastSeen = null);
}
//已经遇到过null了则不做处理
} else if (lastSeen == null || !t.equals(lastSeen)) {
//如果t是第一个处理的元素或者t跟上一个元素不一样,则将其传递给下一个流
//因为是排序好的,所以只可能跟上一个元素重复
downstream.accept(lastSeen = t);
}
}
};
} else {
//如果是一个未排序的流
return new Sink.ChainedReference(sink) {
Set seen;
@Override
public void begin(long size) {
//初始化HashSet
seen = new HashSet<>();
downstream.begin(-1);
}
@Override
public void end() {
seen = null;
downstream.end();
}
@Override
public void accept(T t) {
if (!seen.contains(t)) {
//不包含这个元素,则传递给下一个元素
seen.add(t);
downstream.accept(t);
}
}
};
}
}
};
}
findFirst是查找并返回第一个元素,findAny是返回任意一个元素,其实现如下:
@Override
public final OptionalInt findFirst() {
return evaluate(FindOps.makeInt(true));
}
@Override
public final OptionalInt findAny() {
return evaluate(FindOps.makeInt(false));
}
public static TerminalOp makeInt(boolean mustFindFirst) {
return new FindOp<>(mustFindFirst, StreamShape.INT_VALUE, OptionalInt.empty(),
//最后一个参数sinkSupplier是一个可以通过get方法返回FindSink.OfInt的Supplier
OptionalInt::isPresent, FindSink.OfInt::new);
}
private static final class FindOp implements TerminalOp {
private final StreamShape shape;
final boolean mustFindFirst;
final O emptyValue;
final Predicate presentPredicate;
final Supplier> sinkSupplier;
FindOp(boolean mustFindFirst,
StreamShape shape,
O emptyValue,
Predicate presentPredicate,
Supplier> sinkSupplier) {
this.mustFindFirst = mustFindFirst;
this.shape = shape;
this.emptyValue = emptyValue;
this.presentPredicate = presentPredicate;
this.sinkSupplier = sinkSupplier;
}
@Override
public int getOpFlags() {
//增加IS_SHORT_CIRCUIT标识符,则遍历的过程中如果cancellationRequested方法会true了则会终止遍历
return StreamOpFlag.IS_SHORT_CIRCUIT | (mustFindFirst ? 0 : StreamOpFlag.NOT_ORDERED);
}
@Override
public StreamShape inputShape() {
return shape;
}
@Override
//串行执行时 evaluate方法调用此方法
public O evaluateSequential(PipelineHelper helper,
Spliterator spliterator) {
//wrapAndCopyInto返回一个TerminalSink实现,get方法是其父类Supplier接口的方法
O result = helper.wrapAndCopyInto(sinkSupplier.get(), spliterator).get();
return result != null ? result : emptyValue;
}
@Override
//并行执行时 evaluate方法调用此方法
public O evaluateParallel(PipelineHelper helper,
Spliterator spliterator) {
return new FindTask<>(this, helper, spliterator).invoke();
}
}
private static abstract class FindSink implements TerminalSink {
boolean hasValue;
T value;
FindSink() {} // Avoid creation of special accessor
@Override
public void accept(T value) {
if (!hasValue) {
//如果已经接收了一个元素,则将hasValue置为true
//注意此时没有向下传递流元素,因为find操作是流终止类操作
hasValue = true;
this.value = value;
}
}
@Override
public boolean cancellationRequested() {
//父类默认返回false,如果已经接收了一个元素则返回true
return hasValue;
}
/** Specialization of {@code FindSink} for int streams */
static final class OfInt extends FindSink
implements Sink.OfInt {
@Override
public void accept(int value) {
//调用父类方法
accept((Integer) value);
}
@Override
public OptionalInt get() {
//如果有值则构造一个OptionalInt,否则返回null
return hasValue ? OptionalInt.of(value) : null;
}
}
}
从其实现可知,两者在串行条件下返回的结果是一样的,且找到一个元素后会终止流元素处理,测试用例如下:
@Test
public void test3() throws Exception {
IntStream stream=IntStream.range(1,10);
int a=stream.peek(x->{
System.out.println(x);
// }).findFirst().getAsInt();
}).findAny().getAsInt();
System.out.println(a);
}
findFirst和findAny的输出是一样的,如下:
anyMatch表示任意一个匹配返回true,allMatch所有的都匹配返回true,noneMatch没有一个匹配返回true,其实现如下:
@Override
public final boolean anyMatch(IntPredicate predicate) {
return evaluate(MatchOps.makeInt(predicate, MatchOps.MatchKind.ANY));
}
@Override
public final boolean allMatch(IntPredicate predicate) {
return evaluate(MatchOps.makeInt(predicate, MatchOps.MatchKind.ALL));
}
@Override
public final boolean noneMatch(IntPredicate predicate) {
return evaluate(MatchOps.makeInt(predicate, MatchOps.MatchKind.NONE));
}
//MatchOps的实现
public static TerminalOp makeInt(IntPredicate predicate,
MatchKind matchKind) {
Objects.requireNonNull(predicate);
Objects.requireNonNull(matchKind);
class MatchSink extends BooleanTerminalSink implements Sink.OfInt {
MatchSink() {
super(matchKind);
}
@Override
public void accept(int t) {
//stop默认是false
//ANY时stopOnPredicateMatches为true,ALL时stopOnPredicateMatches为false
//NONE时stopOnPredicateMatches为true,参考后面的MatchKind定义
if (!stop && predicate.test(t) == matchKind.stopOnPredicateMatches) {
stop = true; //变成true,终止遍历
//设置处理结果
value = matchKind.shortCircuitResult;
}
}
}
return new MatchOp<>(StreamShape.INT_VALUE, matchKind, MatchSink::new);
}
private static abstract class BooleanTerminalSink implements Sink {
boolean stop; //是否停止遍历
boolean value; //返回的结果
BooleanTerminalSink(MatchKind matchKind) {
value = !matchKind.shortCircuitResult;
}
public boolean getAndClearState() {
return value;
}
@Override
public boolean cancellationRequested() {
return stop;
}
}
private static final class MatchOp implements TerminalOp {
private final StreamShape inputShape;
final MatchKind matchKind;
final Supplier> sinkSupplier;
MatchOp(StreamShape shape,
MatchKind matchKind,
Supplier> sinkSupplier) {
this.inputShape = shape;
this.matchKind = matchKind;
this.sinkSupplier = sinkSupplier;
}
@Override
public int getOpFlags() {
//加上IS_SHORT_CIRCUIT标识,如果Sink的cancellationRequested返回true则终止流元素遍历
return StreamOpFlag.IS_SHORT_CIRCUIT | StreamOpFlag.NOT_ORDERED;
}
@Override
public StreamShape inputShape() {
return inputShape;
}
@Override
public Boolean evaluateSequential(PipelineHelper helper,
Spliterator spliterator) {
//串行处理时调用
return helper.wrapAndCopyInto(sinkSupplier.get(), spliterator).getAndClearState();
}
@Override
public Boolean evaluateParallel(PipelineHelper helper,
Spliterator spliterator) {
//并行处理时调用
return new MatchTask<>(this, helper, spliterator).invoke();
}
}
enum MatchKind {
/** Do all elements match the predicate? */
ANY(true, true),
/** Do any elements match the predicate? */
ALL(false, false),
/** Do no elements match the predicate? */
NONE(true, false);
private final boolean stopOnPredicateMatches;
private final boolean shortCircuitResult;
private MatchKind(boolean stopOnPredicateMatches,
boolean shortCircuitResult) {
this.stopOnPredicateMatches = stopOnPredicateMatches;
this.shortCircuitResult = shortCircuitResult;
}
}
iterator返回流中元素的遍历器,spliterator返回当前流处理关联的Spliterator实现,其实现如下:
@Override
public final PrimitiveIterator.OfInt iterator() {
return Spliterators.iterator(spliterator());
}
@Override
public final Spliterator.OfInt spliterator() {
return adapt(super.spliterator());
}
public static PrimitiveIterator.OfInt iterator(Spliterator.OfInt spliterator) {
Objects.requireNonNull(spliterator);
class Adapter implements PrimitiveIterator.OfInt, IntConsumer {
boolean valueReady = false;
int nextElement;
@Override
public void accept(int t) {
//接收一个新的流元素
valueReady = true; //表示nextElement是否存在,如果被取走则被置为false
nextElement = t;
}
@Override
public boolean hasNext() {
if (!valueReady)
//tryAdvance会遍历流中的元素,遍历一个后调用上面的accept方法
spliterator.tryAdvance(this);
return valueReady;
}
@Override
public int nextInt() {
if (!valueReady && !hasNext()) //如果nextElement没有且hasNext返回false,说明没有多余的元素了
throw new NoSuchElementException();
else {
valueReady = false;
return nextElement;
}
}
}
return new Adapter();
}
private static Spliterator.OfInt adapt(Spliterator s) {
if (s instanceof Spliterator.OfInt) {
return (Spliterator.OfInt) s;
}
else {
if (Tripwire.ENABLED)
Tripwire.trip(AbstractPipeline.class,
"using IntStream.adapt(Spliterator s)");
throw new UnsupportedOperationException("IntStream.adapt(Spliterator s)");
}
}
onClose表示注册关闭流即执行close时的回调动作,close表示关闭流,注意跟流终止动作关闭流是两码事。
@Override
public void close() {
linkedOrConsumed = true;
sourceSupplier = null;
sourceSpliterator = null;
if (sourceStage.sourceCloseAction != null) {
//如果回调动作不为空的话,则执行回调
Runnable closeAction = sourceStage.sourceCloseAction;
sourceStage.sourceCloseAction = null;
closeAction.run();
}
}
@Override
@SuppressWarnings("unchecked")
public S onClose(Runnable closeHandler) {
Objects.requireNonNull(closeHandler);
Runnable existingHandler = sourceStage.sourceCloseAction;
sourceStage.sourceCloseAction =
(existingHandler == null) //如果没有注册关闭时的回调动作则直接赋值,否则调用composeWithExceptions注册多个
? closeHandler
: Streams.composeWithExceptions(existingHandler, closeHandler);
return (S) this;
}
static Runnable composeWithExceptions(Runnable a, Runnable b) {
//返回一个新的Runnable,同时包裹了a和b,a表示已经存在的回调动作,b表示新增的回调动作
//会保证a先执行,且无论a是否异常,b都会被执行
return new Runnable() {
@Override
public void run() {
try {
a.run();
}
catch (Throwable e1) {
try {
b.run();
}
catch (Throwable e2) {
try {
e1.addSuppressed(e2);
} catch (Throwable ignore) {}
}
throw e1;
}
b.run();
}
};
}