forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathStream.java
1818 lines (1703 loc) · 86.7 KB
/
Stream.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util.stream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Objects;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import java.util.function.UnaryOperator;
import java.util.stream.StreamSpliterators.InfiniteSupplyingSpliterator.OfRef;
import java.util.stream.Streams.StreamBuilderImpl;
import java.util.stream.WhileOps.UnorderedWhileSpliterator.OfRef.Dropping;
import java.util.stream.WhileOps.UnorderedWhileSpliterator.OfRef.Taking;
/**
* A sequence of elements supporting sequential and parallel aggregate
* operations. The following example illustrates an aggregate operation using
* {@link Stream} and {@link IntStream}:
*
* <pre>{@code
* int sum = widgets.stream()
* .filter(w -> w.getColor() == RED)
* .mapToInt(w -> w.getWeight())
* .sum();
* }</pre>
*
* In this example, {@code widgets} is a {@code Collection<Widget>}. We create
* a stream of {@code Widget} objects via {@link Collection#stream Collection.stream()},
* filter it to produce a stream containing only the red widgets, and then
* transform it into a stream of {@code int} values representing the weight of
* each red widget. Then this stream is summed to produce a total weight.
*
* <p>In addition to {@code Stream}, which is a stream of object references,
* there are primitive specializations for {@link IntStream}, {@link LongStream},
* and {@link DoubleStream}, all of which are referred to as "streams" and
* conform to the characteristics and restrictions described here.
*
* <p>To perform a computation, stream
* <a href="package-summary.html#StreamOps">operations</a> are composed into a
* <em>stream pipeline</em>. A stream pipeline consists of a source (which
* might be an array, a collection, a generator function, an I/O channel,
* etc), zero or more <em>intermediate operations</em> (which transform a
* stream into another stream, such as {@link Stream#filter(Predicate)}), and a
* <em>terminal operation</em> (which produces a result or side-effect, such
* as {@link Stream#count()} or {@link Stream#forEach(Consumer)}).
* Streams are lazy; computation on the source data is only performed when the
* terminal operation is initiated, and source elements are consumed only
* as needed.
*
* <p>A stream implementation is permitted significant latitude in optimizing
* the computation of the result. For example, a stream implementation is free
* to elide operations (or entire stages) from a stream pipeline -- and
* therefore elide invocation of behavioral parameters -- if it can prove that
* it would not affect the result of the computation. This means that
* side-effects of behavioral parameters may not always be executed and should
* not be relied upon, unless otherwise specified (such as by the terminal
* operations {@code forEach} and {@code forEachOrdered}). (For a specific
* example of such an optimization, see the API note documented on the
* {@link #count} operation. For more detail, see the
* <a href="package-summary.html#SideEffects">side-effects</a> section of the
* stream package documentation.)
*
* <p>Collections and streams, while bearing some superficial similarities,
* have different goals. Collections are primarily concerned with the efficient
* management of, and access to, their elements. By contrast, streams do not
* provide a means to directly access or manipulate their elements, and are
* instead concerned with declaratively describing their source and the
* computational operations which will be performed in aggregate on that source.
* However, if the provided stream operations do not offer the desired
* functionality, the {@link #iterator()} and {@link #spliterator()} operations
* can be used to perform a controlled traversal.
*
* <p>A stream pipeline, like the "widgets" example above, can be viewed as
* a <em>query</em> on the stream source. Unless the source was explicitly
* designed for concurrent modification (such as a {@link ConcurrentHashMap}),
* unpredictable or erroneous behavior may result from modifying the stream
* source while it is being queried.
*
* <p>Most stream operations accept parameters that describe user-specified
* behavior, such as the lambda expression {@code w -> w.getWeight()} passed to
* {@code mapToInt} in the example above. To preserve correct behavior,
* these <em>behavioral parameters</em>:
* <ul>
* <li>must be <a href="package-summary.html#NonInterference">non-interfering</a>
* (they do not modify the stream source); and</li>
* <li>in most cases must be <a href="package-summary.html#Statelessness">stateless</a>
* (their result should not depend on any state that might change during execution
* of the stream pipeline).</li>
* </ul>
*
* <p>Such parameters are always instances of a
* <a href="../function/package-summary.html">functional interface</a> such
* as {@link java.util.function.Function}, and are often lambda expressions or
* method references. Unless otherwise specified these parameters must be
* <em>non-null</em>.
*
* <p>A stream should be operated on (invoking an intermediate or terminal stream
* operation) only once. This rules out, for example, "forked" streams, where
* the same source feeds two or more pipelines, or multiple traversals of the
* same stream. A stream implementation may throw {@link IllegalStateException}
* if it detects that the stream is being reused. However, since some stream
* operations may return their receiver rather than a new stream object, it may
* not be possible to detect reuse in all cases.
*
* <p>Streams have a {@link #close()} method and implement {@link AutoCloseable}.
* Operating on a stream after it has been closed will throw {@link IllegalStateException}.
* Most stream instances do not actually need to be closed after use, as they
* are backed by collections, arrays, or generating functions, which require no
* special resource management. Generally, only streams whose source is an IO channel,
* such as those returned by {@link Files#lines(Path)}, will require closing. If a
* stream does require closing, it must be opened as a resource within a try-with-resources
* statement or similar control structure to ensure that it is closed promptly after its
* operations have completed.
*
* <p>Stream pipelines may execute either sequentially or in
* <a href="package-summary.html#Parallelism">parallel</a>. This
* execution mode is a property of the stream. Streams are created
* with an initial choice of sequential or parallel execution. (For example,
* {@link Collection#stream() Collection.stream()} creates a sequential stream,
* and {@link Collection#parallelStream() Collection.parallelStream()} creates
* a parallel one.) This choice of execution mode may be modified by the
* {@link #sequential()} or {@link #parallel()} methods, and may be queried with
* the {@link #isParallel()} method.
*
* @param <T> the type of the stream elements
*
* @see IntStream
* @see LongStream
* @see DoubleStream
* @see <a href="package-summary.html">java.util.stream</a>
* @since 1.8
*/
/*
* 流接口,这是完成数据流式操作的基本骨架。
*
* Stream可直译作流,即数据像流一样从Stream上经过,并经过sink的择取。
*
* 一个完整的流通常包含三个阶段:源头阶段、中间阶段、终端阶段。
* 源头阶段的流和中间阶段的流都需要实现Stream接口,而终端阶段不需要实现Stream接口。
* 因此,我们可以认为源头阶段的流和中间阶段的流都是物理上存在的,而终端阶段的流只是一个模拟概念。
*
* Stream封装了三大类操作:创建流、中间操作、终端操作。
* 创建源头阶段的流的操作是显式定义的,而创建中间阶段的流的操作通常在匿名类中完成。
* 对于源头阶段和中间阶段的流,它们都可以调用中间操作和终端操作。
* 但是对于终端阶段的流,由于其实一个概念上的存在,并没有真实地去创建一个Stream,所以不能显式调用中间操作和终端操作。
*
* 在每个流的源头阶段,必须包含一个Spliterator作为数据源,
* 而在非源头阶段,必须包含Sink来决定如何择取元素。
*
* 注:流式操作包含三个要素:Stream、Spliterator、Sink
*/
public interface Stream<T> extends BaseStream<T, Stream<T>> {
/*▼ 创建流的源头阶段 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns an empty sequential {@code Stream}.
*
* @param <T> the type of stream elements
*
* @return an empty sequential stream
*/
// 构造处于源头阶段的流,该流不包含任何待处理元素
static <T> Stream<T> empty() {
// 构造"空"Spliterator(引用类型版本)
Spliterator<T> spliterator = Spliterators.emptySpliterator();
return StreamSupport.stream(spliterator, false);
}
/**
* Returns a sequential {@code Stream} containing a single element.
*
* @param e the single element
* @param <T> the type of stream elements
*
* @return a singleton sequential stream
*/
// 构造处于源头阶段的流,该流仅包含一个元素。当然,该元素可能是多维度的,比如数组或其他容器
static <T> Stream<T> of(T e) {
// 构造单元素流迭代器,流构建器处于[已完成]状态
Spliterator<T> spliterator = new StreamBuilderImpl<>(e);
return StreamSupport.stream(spliterator, false);
}
/**
* Returns a sequential {@code Stream} containing a single element, if
* non-null, otherwise returns an empty {@code Stream}.
*
* @param e the single element
* @param <T> the type of stream elements
*
* @return a stream with a single element if the specified element
* is non-null, otherwise an empty stream
*
* @since 9
*/
/*
* 构造处于源头阶段的流,该流最多仅包含一个元素。
*
* 如果e为null,则执行empty()操作。
* 如果e不为null,则执行of(T)操作。
*/
static <T> Stream<T> ofNullable(T e) {
if(e == null) {
return Stream.empty();
}
Spliterator<T> spliterator = new Streams.StreamBuilderImpl<>(e);
return StreamSupport.stream(spliterator, false);
}
/**
* Creating a stream from an array is safe
*
* Returns a sequential ordered stream whose elements are the specified values.
*
* @param <T> the type of stream elements
* @param values the elements of the new stream
*
* @return the new stream
*/
// 构造处于源头阶段的流,该流包含了指定数组(或类似数组的序列)中的元素
@SafeVarargs
@SuppressWarnings("varargs")
static <T> Stream<T> of(T... values) {
// 内部使用了"数组"Spliterator(引用类型版本)
return Arrays.stream(values);
}
/**
* Returns an infinite sequential ordered {@code Stream} produced by iterative
* application of a function {@code f} to an initial element {@code seed},
* producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
* {@code f(f(seed))}, etc.
*
* <p>The first element (position {@code 0}) in the {@code Stream} will be
* the provided {@code seed}. For {@code n > 0}, the element at position
* {@code n}, will be the result of applying the function {@code f} to the
* element at position {@code n - 1}.
*
* <p>The action of applying {@code f} for one element
* <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>
* the action of applying {@code f} for subsequent elements. For any given
* element the action may be performed in whatever thread the library
* chooses.
*
* @param <T> the type of stream elements
* @param seed the initial element
* @param next a function to be applied to the previous element to produce a new element
*
* @return a new sequential {@code Stream}
*/
/*
* 构造一个包含无限元素的流,仅支持单元素访问(如果遍历,则停不下来)
*
* 该流中的元素特征为:
* 第一个元素是seed,
* 第二个元素是由next处理第一个元素后返回的新元素,
* 第三个元素是由next处理第二个元素后返回的新元素,
* 以此类推...
*/
static <T> Stream<T> iterate(final T seed, final UnaryOperator<T> next) {
Objects.requireNonNull(next);
/*
* 构造Spliterator供Stream使用
*
* 注:没有重写forEachRemaining,tryAdvance也不会返回false,
* 因此,在调用forEachRemaining时将陷入死循环。
*/
Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, Spliterator.ORDERED | Spliterator.IMMUTABLE) {
boolean started; // 是否已经开启了访问
T prev; // 记录上一次访问过的元素
/*
* 尝试用action消费当前流迭代器中下一个元素。
* 此处总是返回true,表示总是"存在"下一个元素。
*
* 注1:该操作可能会引起内部游标的变化
* 注2:该操作可能会顺着sink链向下游传播
*/
@Override
public boolean tryAdvance(Consumer<? super T> action) {
Objects.requireNonNull(action);
T t;
// 如果是首次访问,则需要访问seed
if(!started) {
t = seed;
started = true; // 标记访问已开启
// 如果不是首次访问,则使用fun处理上一次访问过的元素,并返回一个新元素
} else {
t = next.apply(prev);
}
// 记录新元素
prev = t;
// 消费新元素
action.accept(t);
return true;
}
};
// 构造处于源头(head)阶段的流(引用类型版本)
return StreamSupport.stream(spliterator, false);
}
/**
* Returns a sequential ordered {@code Stream} produced by iterative
* application of the given {@code next} function to an initial element,
* conditioned on satisfying the given {@code hasNext} predicate. The
* stream terminates as soon as the {@code hasNext} predicate returns false.
*
* <p>{@code Stream.iterate} should produce the same sequence of elements as
* produced by the corresponding for-loop:
* <pre>{@code
* for (T index=seed; hasNext.test(index); index = next.apply(index)) {
* ...
* }
* }</pre>
*
* <p>The resulting sequence may be empty if the {@code hasNext} predicate
* does not hold on the seed value. Otherwise the first element will be the
* supplied {@code seed} value, the next element (if present) will be the
* result of applying the {@code next} function to the {@code seed} value,
* and so on iteratively until the {@code hasNext} predicate indicates that
* the stream should terminate.
*
* <p>The action of applying the {@code hasNext} predicate to an element
* <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>
* the action of applying the {@code next} function to that element. The
* action of applying the {@code next} function for one element
* <i>happens-before</i> the action of applying the {@code hasNext}
* predicate for subsequent elements. For any given element an action may
* be performed in whatever thread the library chooses.
*
* @param <T> the type of stream elements
* @param seed the initial element
* @param hasNext a predicate to apply to elements to determine when the
* stream must terminate.
* @param next a function to be applied to the previous element to produce
* a new element
*
* @return a new sequential {@code Stream}
*
* @since 9
*/
/*
* 构造一个包含有限元素的流,既支持单元素访问,也支持批量访问(可以遍历)
*
* 该流中的元素特征为:
* 第一个元素是seed,
* 第二个元素是由next处理第一个元素后返回的新元素,
* 第三个元素是由next处理第二个元素后返回的新元素,
* 以此类推...
*
* 如果由next处理生成的新元素被hasNext识别为终止元素,则需要关闭访问
*/
static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) {
Objects.requireNonNull(next);
Objects.requireNonNull(hasNext);
Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, Spliterator.ORDERED | Spliterator.IMMUTABLE) {
boolean started; // 是否已经开启了访问
boolean finished; // 是否已经关闭了访问
T prev; // 记录上一次访问过的元素
/*
* 尝试用action消费当前流迭代器中下一个元素。
* 返回值指示是否找到了下一个元素。
*
* 注1:该操作可能会引起内部游标的变化
* 注2:该操作可能会顺着sink链向下游传播
*/
@Override
public boolean tryAdvance(Consumer<? super T> action) {
Objects.requireNonNull(action);
// 如果已经关闭了访问,直接返回false
if(finished) {
return false;
}
T t;
// 如果是首次访问,则需要访问seed
if(!started) {
t = seed;
started = true; // 标记访问已开启
// 如果不是首次访问,则使用fun处理上一次访问过的元素,并返回一个新元素
} else {
t = next.apply(prev);
}
// 如果遇到了终止元素,则关闭访问
if(!hasNext.test(t)) {
prev = null;
finished = true; // 标记访问已关闭
return false;
}
// 记录新元素
prev = t;
// 消费新元素
action.accept(t);
return true;
}
/*
* 尝试用action逐个消费当前流迭代器中所有剩余元素。
*
* 注1:该操作可能会引起内部游标的变化
* 注2:该操作可能会顺着sink链向下游传播
*/
@Override
public void forEachRemaining(Consumer<? super T> action) {
Objects.requireNonNull(action);
// 如果已经关闭了访问,直接返回false
if(finished) {
return;
}
finished = true;
T t;
// 如果是首次访问,则需要访问seed
if(!started) {
t = seed;
// 如果不是首次访问,则使用fun处理上一次访问过的元素,并返回一个新元素
} else {
t = next.apply(prev);
}
prev = null;
// 遍历剩余的所有元素
while(hasNext.test(t)) {
// 消费新元素
action.accept(t);
// 生成新元素
t = next.apply(t);
}
}
};
// 构造处于源头(head)阶段的流(引用类型版本)
return StreamSupport.stream(spliterator, false);
}
/**
* Returns an infinite sequential unordered stream where each element is
* generated by the provided {@code Supplier}. This is suitable for
* generating constant streams, streams of random elements, etc.
*
* @param <T> the type of stream elements
* @param supplier the {@code Supplier} of generated elements
*
* @return a new infinite sequential unordered {@code Stream}
*/
// 构造一个包含无限元素的流,元素由supplier提供
static <T> Stream<T> generate(Supplier<? extends T> supplier) {
Objects.requireNonNull(supplier);
// "无限"流迭代器(引用类型版本)
Spliterator<T> spliterator = new OfRef<>(Long.MAX_VALUE, supplier);
// 构造处于源头(head)阶段的流(引用类型版本)
return StreamSupport.stream(spliterator, false);
}
/**
* Creates a lazily concatenated stream whose elements are all the
* elements of the first stream followed by all the elements of the
* second stream. The resulting stream is ordered if both
* of the input streams are ordered, and parallel if either of the input
* streams is parallel. When the resulting stream is closed, the close
* handlers for both input streams are invoked.
*
* <p>This method operates on the two input streams and binds each stream
* to its source. As a result subsequent modifications to an input stream
* source may not be reflected in the concatenated stream result.
*
* @param <T> The type of stream elements
* @param s1 the first stream
* @param s2 the second stream
*
* @return the concatenation of the two input streams
*
* @implNote Use caution when constructing streams from repeated concatenation.
* Accessing an element of a deeply concatenated stream can result in deep
* call chains, or even {@code StackOverflowError}.
*
* <p>Subsequent changes to the sequential/parallel execution mode of the
* returned stream are not guaranteed to be propagated to the input streams.
* @apiNote To preserve optimization opportunities this method binds each stream to
* its source and accepts only two streams as parameters. For example, the
* exact size of the concatenated stream source can be computed if the exact
* size of each input stream source is known.
* To concatenate more streams without binding, or without nested calls to
* this method, try creating a stream of streams and flat-mapping with the
* identity function, for example:
* <pre>{@code
* Stream<T> concat = Stream.of(s1, s2, s3, s4).flatMap(s -> s);
* }</pre>
*/
// 构造一个由s1和s2拼接而成的流
static <T> Stream<T> concat(Stream<? extends T> s1, Stream<? extends T> s2) {
Objects.requireNonNull(s1);
Objects.requireNonNull(s2);
// "拼接"流迭代器(引用类型版本)
@SuppressWarnings("unchecked")
Spliterator<T> spliterator = new Streams.ConcatSpliterator.OfRef<>((Spliterator<T>) s1.spliterator(), (Spliterator<T>) s2.spliterator());
// 组合流
Stream<T> stream = StreamSupport.stream(spliterator, s1.isParallel() || s2.isParallel());
// 将两个流的关闭动作串联
Runnable s = Streams.composedClose(s1, s2);
// 为stream注册关闭回调:当stream关闭时,同时将s1和s2也关闭
return stream.onClose(s);
}
/*▲ 创建流的源头阶段 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 中间操作-无状态 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a stream consisting of the elements of this stream that match
* the given predicate.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* predicate to apply to each element to determine if it
* should be included
*
* @return the new stream
*/
// 筛选数据。参数举例:x->x%2==0,筛选出所有偶数
Stream<T> filter(Predicate<? super T> predicate);
/**
* Returns a stream consisting of the results of applying the given
* function to the elements of this stream.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param <R> The element type of the new stream
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to each element
*
* @return the new stream
*/
// 映射数据。参数举例:x->x*x,求平方后返回
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
/**
* Returns an {@code IntStream} consisting of the results of applying the
* given function to the elements of this stream.
*
* <p>This is an <a href="package-summary.html#StreamOps">
* intermediate operation</a>.
*
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to each element
*
* @return the new stream
*/
// 映射数据,返回一个IntStream。参数举例:s->s.length()(要求返回值为int),计算字符串长度
IntStream mapToInt(ToIntFunction<? super T> mapper);
/**
* Returns a {@code LongStream} consisting of the results of applying the
* given function to the elements of this stream.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to each element
*
* @return the new stream
*/
// 映射数据,返回一个LongStream。参考#mapToInt
LongStream mapToLong(ToLongFunction<? super T> mapper);
/**
* Returns a {@code DoubleStream} consisting of the results of applying the
* given function to the elements of this stream.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to each element
*
* @return the new stream
*/
// 映射数据,返回一个DoubleStream。参考#mapToInt
DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper);
/**
* Returns a stream consisting of the results of replacing each element of
* this stream with the contents of a mapped stream produced by applying
* the provided mapping function to each element. Each mapped stream is
* {@link java.util.stream.BaseStream#close() closed} after its contents
* have been placed into this stream. (If a mapped stream is {@code null}
* an empty stream is used, instead.)
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param <R> The element type of the new stream
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to each element which produces a stream
* of new values
*
* @return the new stream
*
* @apiNote The {@code flatMap()} operation has the effect of applying a one-to-many
* transformation to the elements of the stream, and then flattening the
* resulting elements into a new stream.
*
* <p><b>Examples.</b>
*
* <p>If {@code orders} is a stream of purchase orders, and each purchase
* order contains a collection of line items, then the following produces a
* stream containing all the line items in all the orders:
* <pre>{@code
* orders.flatMap(order -> order.getLineItems().stream())...
* }</pre>
*
* <p>If {@code path} is the path to a file, then the following produces a
* stream of the {@code words} contained in that file:
* <pre>{@code
* Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8);
* Stream<String> words = lines.flatMap(line -> Stream.of(line.split(" +")));
* }</pre>
* The {@code mapper} function passed to {@code flatMap} splits a line,
* using a simple regular expression, into an array of words, and then
* creates a stream of words from that array.
*/
/*
* 数据降维。参数举例:l->l.stream()。
*
* 比如int[][] a = new int[]{new int[]{1,2,3}, new int[]{4,5}. new int[]{6}};,降维成一维数组:[1,2,3,4,5,6]
* 注:一次只能降低一个维度,比如遇到三维数组,那么如果想要得到一维的数据,需要连续调用两次。
*
* mapper的作用就是将上游的高维容器中的元素提取出来放到流中,并在后续将该元素依次传递到下游,
* 这就相当于把原来的元素从高维容器中提取出来了。
*/
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
/**
* Returns an {@code IntStream} consisting of the results of replacing each
* element of this stream with the contents of a mapped stream produced by
* applying the provided mapping function to each element. Each mapped
* stream is {@link java.util.stream.BaseStream#close() closed} after its
* contents have been placed into this stream. (If a mapped stream is
* {@code null} an empty stream is used, instead.)
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to each element which produces a stream
* of new values
*
* @return the new stream
*
* @see #flatMap(Function)
*/
// 数据降维。参考#flatMap。
IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper);
/**
* Returns an {@code LongStream} consisting of the results of replacing each
* element of this stream with the contents of a mapped stream produced by
* applying the provided mapping function to each element. Each mapped
* stream is {@link java.util.stream.BaseStream#close() closed} after its
* contents have been placed into this stream. (If a mapped stream is
* {@code null} an empty stream is used, instead.)
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to each element which produces a stream
* of new values
*
* @return the new stream
*
* @see #flatMap(Function)
*/
// 数据降维。参考#flatMap。
LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper);
/**
* Returns an {@code DoubleStream} consisting of the results of replacing
* each element of this stream with the contents of a mapped stream produced
* by applying the provided mapping function to each element. Each mapped
* stream is {@link java.util.stream.BaseStream#close() closed} after its
* contents have placed been into this stream. (If a mapped stream is
* {@code null} an empty stream is used, instead.)
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to each element which produces a stream
* of new values
*
* @return the new stream
*
* @see #flatMap(Function)
*/
// 数据降维。参考#flatMap。
DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper);
/**
* Returns a stream consisting of the elements of this stream, additionally
* performing the provided action on each element as elements are consumed
* from the resulting stream.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* <p>For parallel stream pipelines, the action may be called at
* whatever time and in whatever thread the element is made available by the
* upstream operation. If the action modifies shared state,
* it is responsible for providing the required synchronization.
*
* @param action a <a href="package-summary.html#NonInterference">
* non-interfering</a> action to perform on the elements as
* they are consumed from the stream
*
* @return the new stream
*
* @apiNote This method exists mainly to support debugging, where you want
* to see the elements as they flow past a certain point in a pipeline:
* <pre>{@code
* Stream.of("one", "two", "three", "four")
* .filter(e -> e.length() > 3)
* .peek(e -> System.out.println("Filtered value: " + e))
* .map(String::toUpperCase)
* .peek(e -> System.out.println("Mapped value: " + e))
* .collect(Collectors.toList());
* }</pre>
*
* <p>In cases where the stream implementation is able to optimize away the
* production of some or all the elements (such as with short-circuiting
* operations like {@code findFirst}, or in the example described in
* {@link #count}), the action will not be invoked for those elements.
*/
/*
* 用于查看流的内部结构,不会对流的结构产生影响。
* peek常用来查看当前流的结构,比如输出其中的元素。
*/
Stream<T> peek(Consumer<? super T> action);
/*▲ 中间操作-无状态 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 中间操作-有状态 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a stream consisting of the distinct elements (according to
* {@link Object#equals(Object)}) of this stream.
*
* <p>For ordered streams, the selection of distinct elements is stable
* (for duplicated elements, the element appearing first in the encounter
* order is preserved.) For unordered streams, no stability guarantees
* are made.
*
* <p>This is a <a href="package-summary.html#StreamOps">stateful
* intermediate operation</a>.
*
* @return the new stream
*
* @apiNote Preserving stability for {@code distinct()} in parallel pipelines is
* relatively expensive (requires that the operation act as a full barrier,
* with substantial buffering overhead), and stability is often not needed.
* Using an unordered stream source (such as {@link #generate(Supplier)})
* or removing the ordering constraint with {@link #unordered()} may result
* in significantly more efficient execution for {@code distinct()} in parallel
* pipelines, if the semantics of your situation permit. If consistency
* with encounter order is required, and you are experiencing poor performance
* or memory utilization with {@code distinct()} in parallel pipelines,
* switching to sequential execution with {@link #sequential()} may improve
* performance.
*/
// 去重
Stream<T> distinct();
/**
* Returns a stream consisting of the elements of this stream, sorted
* according to natural order. If the elements of this stream are not
* {@code Comparable}, a {@code java.lang.ClassCastException} may be thrown
* when the terminal operation is executed.
*
* <p>For ordered streams, the sort is stable. For unordered streams, no
* stability guarantees are made.
*
* <p>This is a <a href="package-summary.html#StreamOps">stateful
* intermediate operation</a>.
*
* @return the new stream
*/
// 排序(默认升序)
Stream<T> sorted();
/**
* Returns a stream consisting of the elements of this stream, sorted
* according to the provided {@code Comparator}.
*
* <p>For ordered streams, the sort is stable. For unordered streams, no
* stability guarantees are made.
*
* <p>This is a <a href="package-summary.html#StreamOps">stateful
* intermediate operation</a>.
*
* @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* {@code Comparator} to be used to compare stream elements
*
* @return the new stream
*/
// 排序(使用comparator制定排序规则)
Stream<T> sorted(Comparator<? super T> comparator);
/**
* Returns a stream consisting of the elements of this stream, truncated
* to be no longer than {@code maxSize} in length.
*
* <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
* stateful intermediate operation</a>.
*
* @param maxSize the number of elements the stream should be limited to
*
* @return the new stream
*
* @throws IllegalArgumentException if {@code maxSize} is negative
* @apiNote While {@code limit()} is generally a cheap operation on sequential
* stream pipelines, it can be quite expensive on ordered parallel pipelines,
* especially for large values of {@code maxSize}, since {@code limit(n)}
* is constrained to return not just any <em>n</em> elements, but the
* <em>first n</em> elements in the encounter order. Using an unordered
* stream source (such as {@link #generate(Supplier)}) or removing the
* ordering constraint with {@link #unordered()} may result in significant
* speedups of {@code limit()} in parallel pipelines, if the semantics of
* your situation permit. If consistency with encounter order is required,
* and you are experiencing poor performance or memory utilization with
* {@code limit()} in parallel pipelines, switching to sequential execution
* with {@link #sequential()} may improve performance.
*/
// 只显示前maxSize个元素
Stream<T> limit(long maxSize);
/**
* Returns a stream consisting of the remaining elements of this stream
* after discarding the first {@code n} elements of the stream.
* If this stream contains fewer than {@code n} elements then an
* empty stream will be returned.
*
* <p>This is a <a href="package-summary.html#StreamOps">stateful
* intermediate operation</a>.
*
* @param n the number of leading elements to skip
*
* @return the new stream
*
* @throws IllegalArgumentException if {@code n} is negative
* @apiNote While {@code skip()} is generally a cheap operation on sequential
* stream pipelines, it can be quite expensive on ordered parallel pipelines,
* especially for large values of {@code n}, since {@code skip(n)}
* is constrained to skip not just any <em>n</em> elements, but the
* <em>first n</em> elements in the encounter order. Using an unordered
* stream source (such as {@link #generate(Supplier)}) or removing the
* ordering constraint with {@link #unordered()} may result in significant
* speedups of {@code skip()} in parallel pipelines, if the semantics of
* your situation permit. If consistency with encounter order is required,
* and you are experiencing poor performance or memory utilization with
* {@code skip()} in parallel pipelines, switching to sequential execution
* with {@link #sequential()} may improve performance.
*/
// 跳过前n个元素
Stream<T> skip(long n);
/**
* Returns, if this stream is ordered, a stream consisting of the longest
* prefix of elements taken from this stream that match the given predicate.
* Otherwise returns, if this stream is unordered, a stream consisting of a
* subset of elements taken from this stream that match the given predicate.
*
* <p>If this stream is ordered then the longest prefix is a contiguous
* sequence of elements of this stream that match the given predicate. The
* first element of the sequence is the first element of this stream, and
* the element immediately following the last element of the sequence does
* not match the given predicate.
*
* <p>If this stream is unordered, and some (but not all) elements of this
* stream match the given predicate, then the behavior of this operation is
* nondeterministic; it is free to take any subset of matching elements
* (which includes the empty set).
*
* <p>Independent of whether this stream is ordered or unordered if all
* elements of this stream match the given predicate then this operation
* takes all elements (the result is the same as the input), or if no
* elements of the stream match the given predicate then no elements are
* taken (the result is an empty stream).
*
* <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
* stateful intermediate operation</a>.
*
* @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* predicate to apply to elements to determine the longest
* prefix of elements.
*
* @return the new stream
*
* @implSpec The default implementation obtains the {@link #spliterator() spliterator}
* of this stream, wraps that spliterator so as to support the semantics
* of this operation on traversal, and returns a new stream associated with
* the wrapped spliterator. The returned stream preserves the execution
* characteristics of this stream (namely parallel or sequential execution
* as per {@link #isParallel()}) but the wrapped spliterator may choose to
* not support splitting. When the returned stream is closed, the close
* handlers for both the returned and this stream are invoked.
* @apiNote While {@code takeWhile()} is generally a cheap operation on sequential
* stream pipelines, it can be quite expensive on ordered parallel
* pipelines, since the operation is constrained to return not just any
* valid prefix, but the longest prefix of elements in the encounter order.
* Using an unordered stream source (such as {@link #generate(Supplier)}) or