PipelineHelper类里的方法:wrapAndCopyInto()
/** * Applies the pipeline stages described by this {@code PipelineHelper} to * the provided {@code Spliterator} and send the results to the provided * {@code Sink}. 将调用了这个方法的pipeline所描述的管道的各个阶段,同时 应用到Spliterator和发送给Sink对象 * * @implSpec * The implementation behaves as if: * <pre>{@code * intoWrapped(wrapSink(sink), spliterator); * }</pre> * * @param sink the {@code Sink} to receive the results * @param spliterator the spliterator describing the source input to process */ abstract<P_IN, S extends Sink<P_OUT>> S wrapAndCopyInto(S sink, Spliterator<P_IN> spliterator);wrapAndCopyInto具体实现:
@Override final <P_IN, S extends Sink<E_OUT>> S wrapAndCopyInto(S sink, Spliterator<P_IN> spliterator) { copyInto(wrapSink(Objects.requireNonNull(sink)), spliterator); return sink; }Sink中的wrapSink()方法
/** * Takes a {@code Sink} that accepts elements of the output type of the * {@code PipelineHelper}, and wrap it with a {@code Sink} that accepts * elements of the input type and implements all the intermediate operations * described by this {@code PipelineHelper}, delivering the result into the * provided {@code Sink}. 接受了一个Sink, Sink接受了PipelineHelper的所有输出类型。 * * @param sink the {@code Sink} to receive the results * @return a {@code Sink} that implements the pipeline stages and sends * results to the provided {@code Sink} */ abstract<P_IN> Sink<P_IN> wrapSink(Sink<P_OUT> sink);wrapSink()方法具体实现 (完成了对于多个流操作的串联。)
@Override @SuppressWarnings("unchecked") final <P_IN> Sink<P_IN> wrapSink(Sink<E_OUT> sink) { Objects.requireNonNull(sink); //根据depth判断是否有中间操作。 从后往前的去走。 for ( @SuppressWarnings("rawtypes") AbstractPipeline p=AbstractPipeline.this; p.depth > 0; p=p.previousStage) { sink = p.opWrapSink(p.previousStage.combinedFlags, sink); } return (Sink<P_IN>) sink; }wrapSink()
自我总结:Stream的执行流程。源数据-中间操作-中间操作-终止操作
1.串联起来所有的操作。(中间操作 和 终止操作)
2.让流中的元素,一个一个的执行所含有的所有操作。
最核心的方法:copyInto()中的:spliterator.forEachRemaining(wrappedSink); //最最核心的一步
@Override final <P_IN> void copyInto(Sink<P_IN> wrappedSink, Spliterator<P_IN> spliterator) { Objects.requireNonNull(wrappedSink); if (!StreamOpFlag.SHORT_CIRCUIT.isKnown(getStreamAndOpFlags())) { wrappedSink.begin(spliterator.getExactSizeIfKnown()); spliterator.forEachRemaining(wrappedSink); //最最核心的一步 wrappedSink.end(); } else { copyIntoWithCancel(wrappedSink, spliterator); } }wrappedSink : 所有的中间操作,封装到了这个 sink对象
spliterator:源数据- 执行forEachRemaining 遍历,执行每一次这过sink对象封装的操作。
上面是静态分析(通过源码分析)
自行通过动态分析(程序Debug分析)
t通过Debug去跟一遍代码。
public class StreamTest3 { public static void main(String[] args) { List<String> list = Arrays.asList("hello", "world", "welcome"); // list.stream().map(item->item+"_abc").forEach(System.out::println); Stream<String> stream = list.stream(); System.out.println("1");//断点 Stream<String> stream1 = stream.map(item -> item + "_abc"); System.out.println("2");//断点 stream1.forEach(System.out::println); } }