forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCollectors.java
2961 lines (2628 loc) · 140 KB
/
Collectors.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.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IntSummaryStatistics;
import java.util.Iterator;
import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
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.Predicate;
import java.util.function.Supplier;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import java.util.stream.Collector.Characteristics;
/**
* Implementations of {@link Collector} that implement various useful reduction
* operations, such as accumulating elements into collections, summarizing
* elements according to various criteria, etc.
*
* <p>The following are examples of using the predefined collectors to perform
* common mutable reduction tasks:
*
* <pre>{@code
* // Accumulate names into a List
* List<String> list = people.stream()
* .map(Person::getName)
* .collect(Collectors.toList());
*
* // Accumulate names into a TreeSet
* Set<String> set = people.stream()
* .map(Person::getName)
* .collect(Collectors.toCollection(TreeSet::new));
*
* // Convert elements to strings and concatenate them, separated by commas
* String joined = things.stream()
* .map(Object::toString)
* .collect(Collectors.joining(", "));
*
* // Compute sum of salaries of employee
* int total = employees.stream()
* .collect(Collectors.summingInt(Employee::getSalary));
*
* // Group employees by department
* Map<Department, List<Employee>> byDept = employees.stream()
* .collect(Collectors.groupingBy(Employee::getDepartment));
*
* // Compute sum of salaries by department
* Map<Department, Integer> totalByDept = employees.stream()
* .collect(Collectors.groupingBy(Employee::getDepartment,
* Collectors.summingInt(Employee::getSalary)));
*
* // Partition students into passing and failing
* Map<Boolean, List<Student>> passingFailing = students.stream()
* .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
*
* }</pre>
*
* @since 1.8
*/
/*
* 收集器(Collector)工厂
*
* 该工厂中允许定制各种收集器,以完成不同的收集操作。
*/
public final class Collectors {
// 未设置任何参数
static final Set<Collector.Characteristics> CH_NOID = Collections.emptySet();
// 并发容器/无序收集/无需收尾
static final Set<Collector.Characteristics> CH_CONCURRENT_ID = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.CONCURRENT, Collector.Characteristics.UNORDERED, Collector.Characteristics.IDENTITY_FINISH));
// 并发容器/无序收集
static final Set<Collector.Characteristics> CH_CONCURRENT_NOID = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.CONCURRENT, Collector.Characteristics.UNORDERED));
// 无序收集/无需收尾
static final Set<Collector.Characteristics> CH_UNORDERED_ID = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.UNORDERED, Collector.Characteristics.IDENTITY_FINISH));
// 无序收集
static final Set<Collector.Characteristics> CH_UNORDERED_NOID = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.UNORDERED));
// 无需收尾
static final Set<Collector.Characteristics> CH_ID = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
private Collectors() {
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 简单收集 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a {@code Collector} that accumulates the input elements into a
* new {@code Collection}, in encounter order. The {@code Collection} is
* created by the provided factory.
*
* @param <T> the type of the input elements
* @param <C> the type of the resulting {@code Collection}
* @param collectionFactory a supplier providing a new empty {@code Collection}
* into which the results will be inserted
*
* @return a {@code Collector} which collects all the input elements into a
* {@code Collection}, in encounter order
*/
// 收集元素到自定义容器
public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 由入参提供。
*/
Supplier<C> supplier = collectionFactory;
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 将遇到的元素添加到容器中。
*/
BiConsumer<C, T> accumulator = Collection::add;
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 将后一个容器中的元素添加到前一个容器中,并返回前一个容器。
*/
BinaryOperator<C> combiner = (collection1, collection2) -> {
collection1.addAll(collection2);
return collection1;
};
/*
* 5.容器参数,指示容器的特征。
* 无需收尾。
*/
Set<Characteristics> characteristics = CH_ID;
return new CollectorImpl<>(supplier, accumulator, combiner, characteristics);
}
/**
* Returns a {@code Collector} that accumulates the input elements into a
* new {@code List}. There are no guarantees on the type, mutability,
* serializability, or thread-safety of the {@code List} returned; if more
* control over the returned {@code List} is required, use {@link #toCollection(Supplier)}.
*
* @param <T> the type of the input elements
*
* @return a {@code Collector} which collects all the input elements into a
* {@code List}, in encounter order
*/
// 收集元素到ArrayList容器
public static <T> Collector<T, ?, List<T>> toList() {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 构造一个ArrayList。
*/
Supplier<List<T>> supplier = (Supplier<List<T>>) ArrayList::new;
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 将遇到的元素添加到容器中。
*/
BiConsumer<List<T>, T> accumulator = List::add;
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 将后一个容器中的元素添加到前一个容器中,并返回前一个容器。
*/
BinaryOperator<List<T>> combiner = (list1, list2) -> {
list1.addAll(list2);
return list1;
};
/*
* 5.容器参数,指示容器的特征。
* 无需收尾。
*/
Set<Characteristics> characteristics = CH_ID;
return new CollectorImpl<>(supplier, accumulator, combiner, characteristics);
}
/**
* Returns a {@code Collector} that accumulates the input elements into an
* <a href="../List.html#unmodifiable">unmodifiable List</a> in encounter
* order. The returned Collector disallows null values and will throw
* {@code NullPointerException} if it is presented with a null value.
*
* @param <T> the type of the input elements
*
* @return a {@code Collector} that accumulates the input elements into an
* <a href="../List.html#unmodifiable">unmodifiable List</a> in encounter order
*
* @since 10
*/
// 收集元素到只读的List容器
@SuppressWarnings("unchecked")
public static <T> Collector<T, ?, List<T>> toUnmodifiableList() {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 构造一个ArrayList。
*/
Supplier<List<T>> supplier = (Supplier<List<T>>) ArrayList::new;
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 将遇到的元素添加到容器中。
*/
BiConsumer<List<T>, T> accumulator = List::add;
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 将后一个容器中的元素添加到前一个容器中,并返回前一个容器。
*/
BinaryOperator<List<T>> combiner = (list1, list2) -> {
list1.addAll(list2);
return list1;
};
/*
* 4.收尾操作(可选,最后执行)。
* 将之前收集到的元素存入一个只读容器后返回。
*/
Function<List<T>, List<T>> finisher = list -> (List<T>) List.of(list.toArray());
/*
* 5.容器参数,指示容器的特征。
* 未设置任何参数。
*/
Set<Characteristics> characteristics = CH_NOID;
return new CollectorImpl<>(supplier, accumulator, combiner, finisher, characteristics);
}
/**
* Returns a {@code Collector} that accumulates the input elements into a
* new {@code Set}. There are no guarantees on the type, mutability,
* serializability, or thread-safety of the {@code Set} returned; if more
* control over the returned {@code Set} is required, use
* {@link #toCollection(Supplier)}.
*
* <p>This is an {@link Collector.Characteristics#UNORDERED unordered}
* Collector.
*
* @param <T> the type of the input elements
*
* @return a {@code Collector} which collects all the input elements into a
* {@code Set}
*/
// 收集元素到HashSet容器
public static <T> Collector<T, ?, Set<T>> toSet() {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 构造一个HashSet。
*/
Supplier<Set<T>> supplier = (Supplier<Set<T>>) HashSet::new;
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 将遇到的元素添加到容器中。
*/
BiConsumer<Set<T>, T> accumulator = Set::add;
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 将小容量容器中的元素添加到大容量容器中,这样做可以节省一定的时间。
*/
BinaryOperator<Set<T>> combiner = (left, right) -> {
if(left.size()<right.size()) {
right.addAll(left);
return right;
} else {
left.addAll(right);
return left;
}
};
/*
* 5.容器参数,指示容器的特征。
* 无序收集/无需收尾。
*/
Set<Characteristics> characteristics = CH_UNORDERED_ID;
return new CollectorImpl<>(supplier, accumulator, combiner, characteristics);
}
/**
* Returns a {@code Collector} that accumulates the input elements into an
* <a href="../Set.html#unmodifiable">unmodifiable Set</a>. The returned
* Collector disallows null values and will throw {@code NullPointerException}
* if it is presented with a null value. If the input contains duplicate elements,
* an arbitrary element of the duplicates is preserved.
*
* <p>This is an {@link Collector.Characteristics#UNORDERED unordered}
* Collector.
*
* @param <T> the type of the input elements
*
* @return a {@code Collector} that accumulates the input elements into an
* <a href="../Set.html#unmodifiable">unmodifiable Set</a>
*
* @since 10
*/
// 收集元素到只读的Set容器
@SuppressWarnings("unchecked")
public static <T> Collector<T, ?, Set<T>> toUnmodifiableSet() {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 构造一个HashSet。
*/
Supplier<Set<T>> supplier = (Supplier<Set<T>>) HashSet::new;
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 将遇到的元素添加到容器中。
*/
BiConsumer<Set<T>, T> accumulator = Set::add;
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 将小容量容器中的元素添加到大容量容器中,这样做可以节省一定的时间。
*/
BinaryOperator<Set<T>> combiner = (left, right) -> {
if(left.size()<right.size()) {
right.addAll(left);
return right;
} else {
left.addAll(right);
return left;
}
};
/*
* 4.收尾操作(可选,最后执行)。
* 将之前收集到的元素存入一个只读容器后返回。
*/
Function<Set<T>, Set<T>> finisher = set -> (Set<T>) Set.of(set.toArray());
/*
* 5.容器参数,指示容器的特征。
* 无序收集
*/
Set<Characteristics> characteristics = CH_UNORDERED_NOID;
return new CollectorImpl<>(supplier, accumulator, combiner, characteristics);
}
/**
* Returns a {@code Collector} that concatenates the input elements into a
* {@code String}, in encounter order.
*
* @return a {@code Collector} that concatenates the input elements into a
* {@code String}, in encounter order
*/
// 收集字符串到StringBuilder容器,并转换为String后返回
public static Collector<CharSequence, ?, String> joining() {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 构造一个StringBuilder。
*/
Supplier<StringBuilder> supplier = StringBuilder::new;
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 将遇到的元素添加到容器中。
*/
BiConsumer<StringBuilder, CharSequence> accumulator = StringBuilder::append;
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 将后一个容器中的元素添加到前一个容器中,并返回前一个容器。
*/
BinaryOperator<StringBuilder> combiner = (builder, charSequence) -> {
builder.append(charSequence);
return builder;
};
/*
* 4.收尾操作(可选,最后执行)。
* 将之前收集到的字符序列转换为String后返回。
*/
Function<StringBuilder, String> finisher = StringBuilder::toString;
/*
* 5.容器参数,指示容器的特征。
* 未设置任何参数。
*/
Set<Characteristics> characteristics = CH_NOID;
return new CollectorImpl<>(supplier, accumulator, combiner, finisher, characteristics);
}
/**
* Returns a {@code Collector} that concatenates the input elements,
* separated by the specified delimiter, in encounter order.
*
* @param delimiter the delimiter to be used between each element
*
* @return A {@code Collector} which concatenates CharSequence elements,
* separated by the specified delimiter, in encounter order
*/
// 收集字符串到StringJoiner容器,并转换为String后返回;字符串之间使用delimiter分割
public static Collector<CharSequence, ?, String> joining(CharSequence delimiter) {
return joining(delimiter, "", "");
}
/**
* Returns a {@code Collector} that concatenates the input elements,
* separated by the specified delimiter, with the specified prefix and
* suffix, in encounter order.
*
* @param delimiter the delimiter to be used between each element
* @param prefix the sequence of characters to be used at the beginning
* of the joined result
* @param suffix the sequence of characters to be used at the end
* of the joined result
*
* @return A {@code Collector} which concatenates CharSequence elements,
* separated by the specified delimiter, in encounter order
*/
// 收集字符串到StringJoiner容器,并转换为String后返回;字符串之间使用delimiter分割,并且带有前缀prefix和后缀suffix
public static Collector<CharSequence, ?, String> joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 构造一个StringJoiner。
*/
Supplier<StringJoiner> supplier = () -> new StringJoiner(delimiter, prefix, suffix);
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 将遇到的元素添加到容器中。
*/
BiConsumer<StringJoiner, CharSequence> accumulator = StringJoiner::add;
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 将后一个容器中的元素添加到前一个容器中,并返回前一个容器。
*/
BinaryOperator<StringJoiner> combiner = StringJoiner::merge;
/*
* 4.收尾操作(可选,最后执行)。
* 将之前收集到的字符序列转换为String后返回。
*/
Function<StringJoiner, String> finisher = StringJoiner::toString;
/*
* 5.容器参数,指示容器的特征。
* 未设置任何参数。
*/
Set<Characteristics> characteristics = CH_NOID;
return new CollectorImpl<>(supplier, accumulator, combiner, finisher, characteristics);
}
/*▲ 简单收集 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 过滤 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Adapts a {@code Collector} to one accepting elements of the same type
* {@code T} by applying the predicate to each input element and only
* accumulating if the predicate returns {@code true}.
*
* @param <T> the type of the input elements
* @param <A> intermediate accumulation type of the downstream collector
* @param <R> result type of collector
* @param predicate a predicate to be applied to the input elements
* @param downstream a collector which will accept values that match the predicate
*
* @return a collector which applies the predicate to the input elements
* and provides matching elements to the downstream collector
*
* @apiNote The {@code filtering()} collectors are most useful when used in a
* multi-level reduction, such as downstream of a {@code groupingBy} or
* {@code partitioningBy}. For example, given a stream of
* {@code Employee}, to accumulate the employees in each department that have a
* salary above a certain threshold:
* <pre>{@code
* Map<Department, Set<Employee>> wellPaidEmployeesByDepartment
* = employees.stream().collect(
* groupingBy(Employee::getDepartment,
* filtering(e -> e.getSalary() > 2000,
* toSet())));
* }</pre>
* A filtering collector differs from a stream's {@code filter()} operation.
* In this example, suppose there are no employees whose salary is above the
* threshold in some department. Using a filtering collector as shown above
* would result in a mapping from that department to an empty {@code Set}.
* If a stream {@code filter()} operation were done instead, there would be
* no mapping for that department at all.
* @since 9
*/
// 对上游的数据进行过滤:只保存符合predicate条件的元素,过滤后存储到downstream中
public static <T, A, R> Collector<T, ?, R> filtering(Predicate<? super T> predicate, Collector<? super T, A, R> downstream) {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 使用downstream中的容器工厂。
*/
Supplier<A> supplier = downstream.supplier();
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 使用downstream中的择取操作,但是择取每个元素之前,必须先使用predicate对元素过滤,保留满足条件的元素。
*/
BiConsumer<A, T> accumulator = (r, t) -> {
if(predicate.test(t)) {
downstream.accumulator().accept(r, t);
}
};
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 使用downstream中的合并操作。
*/
BinaryOperator<A> combiner = downstream.combiner();
/*
* 4.收尾操作(可选,最后执行)。
* 使用downstream中的收尾操作。
*/
Function<A, R> finisher = downstream.finisher();
/*
* 5.容器参数,指示容器的特征。
* 使用downstream中的容器参数。
*/
Set<Characteristics> characteristics = downstream.characteristics();
return new CollectorImpl<>(supplier, accumulator, combiner, finisher, characteristics);
}
/*▲ 过滤 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 映射 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Adapts a {@code Collector} accepting elements of type {@code U} to one
* accepting elements of type {@code T} by applying a mapping function to
* each input element before accumulation.
*
* @param <T> the type of the input elements
* @param <U> type of elements accepted by downstream collector
* @param <A> intermediate accumulation type of the downstream collector
* @param <R> result type of collector
* @param mapper a function to be applied to the input elements
* @param downstream a collector which will accept mapped values
*
* @return a collector which applies the mapping function to the input
* elements and provides the mapped results to the downstream collector
*
* @apiNote The {@code mapping()} collectors are most useful when used in a
* multi-level reduction, such as downstream of a {@code groupingBy} or
* {@code partitioningBy}. For example, given a stream of
* {@code Person}, to accumulate the set of last names in each city:
* <pre>{@code
* Map<City, Set<String>> lastNamesByCity
* = people.stream().collect(
* groupingBy(Person::getCity,
* mapping(Person::getLastName,
* toSet())));
* }</pre>
*/
// 对上游的数据进行映射:将上游的元素使用mapper映射后再保存,映射后存储到downstream中
public static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper, Collector<? super U, A, R> downstream) {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 使用downstream中的容器工厂。
*/
Supplier<A> supplier = downstream.supplier();
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 使用downstream中的择取操作,但是择取每个元素之前,必须先使用mapper对元素映射,保留转换之后的元素。
*/
BiConsumer<A, T> accumulator = (r, t) -> downstream.accumulator().accept(r, mapper.apply(t));
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 使用downstream中的合并操作。
*/
BinaryOperator<A> combiner = downstream.combiner();
/*
* 4.收尾操作(可选,最后执行)。
* 使用downstream中的收尾操作。
*/
Function<A, R> finisher = downstream.finisher();
/*
* 5.容器参数,指示容器的特征。
* 使用downstream中的容器参数。
*/
Set<Characteristics> characteristics = downstream.characteristics();
return new CollectorImpl<>(supplier, accumulator, combiner, finisher, characteristics);
}
/*▲ 映射 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 降维 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Adapts a {@code Collector} accepting elements of type {@code U} to one
* accepting elements of type {@code T} by applying a flat mapping function
* to each input element before accumulation. The flat mapping function
* maps an input element to a {@link Stream stream} covering zero or more
* output elements that are then accumulated downstream. Each mapped stream
* is {@link java.util.stream.BaseStream#close() closed} after its contents
* have been placed downstream. (If a mapped stream is {@code null}
* an empty stream is used, instead.)
*
* @param <T> the type of the input elements
* @param <U> type of elements accepted by downstream collector
* @param <A> intermediate accumulation type of the downstream collector
* @param <R> result type of collector
* @param mapper a function to be applied to the input elements, which
* returns a stream of results
* @param downstream a collector which will receive the elements of the
* stream returned by mapper
*
* @return a collector which applies the mapping function to the input
* elements and provides the flat mapped results to the downstream collector
*
* @apiNote The {@code flatMapping()} collectors are most useful when used in a
* multi-level reduction, such as downstream of a {@code groupingBy} or
* {@code partitioningBy}. For example, given a stream of
* {@code Order}, to accumulate the set of line items for each customer:
* <pre>{@code
* Map<String, Set<LineItem>> itemsByCustomerName
* = orders.stream().collect(
* groupingBy(Order::getCustomerName,
* flatMapping(order -> order.getLineItems().stream(),
* toSet())));
* }</pre>
* @since 9
*/
// 对上游的数据进行降维:如果上游的元素本身是一个容器,则将该容器中的元素逐一选出来,再存入downstream中;mapper的作用是将上游的元素流化
public static <T, U, A, R> Collector<T, ?, R> flatMapping(Function<? super T, ? extends Stream<? extends U>> mapper, Collector<? super U, A, R> downstream) {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 使用downstream中的容器工厂。
*/
Supplier<A> supplier = downstream.supplier();
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 使用downstream中的择取操作,但是择取每个元素之前,必须先将该元素内的子元素分别取出来,再对其进行择取,则相当于"降维"。
*/
BiConsumer<A, T> accumulator = (r, t) -> {
try(Stream<? extends U> result = mapper.apply(t)) {
if(result != null) {
result.sequential().forEach(u -> downstream.accumulator().accept(r, u));
}
}
};
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 使用downstream中的合并操作。
*/
BinaryOperator<A> combiner = downstream.combiner();
/*
* 4.收尾操作(可选,最后执行)。
* 使用downstream中的收尾操作。
*/
Function<A, R> finisher = downstream.finisher();
/*
* 5.容器参数,指示容器的特征。
* 使用downstream中的容器参数。
*/
Set<Characteristics> characteristics = downstream.characteristics();
return new CollectorImpl<>(supplier, accumulator, combiner, finisher, characteristics);
}
/*▲ 降维 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 后处理 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Adapts a {@code Collector} to perform an additional finishing
* transformation. For example, one could adapt the {@link #toList()}
* collector to always produce an immutable list with:
* <pre>{@code
* List<String> list = people.stream().collect(
* collectingAndThen(toList(),
* Collections::unmodifiableList));
* }</pre>
*
* @param <T> the type of the input elements
* @param <A> intermediate accumulation type of the downstream collector
* @param <R> result type of the downstream collector
* @param <RR> result type of the resulting collector
* @param downstream a collector
* @param finisher a function to be applied to the final result of the downstream collector
*
* @return a collector which performs the action of the downstream collector,
* followed by an additional finishing step
*/
// 对上游的数据进行后处理:对上游的元素先使用downstream中的收尾操作处理,再使用thenFinisher这个收尾操作处理;后处理的结果存储到downstream中
public static <T, A, R, RR> Collector<T, A, RR> collectingAndThen(Collector<T, A, R> downstream, Function<R, RR> thenFinisher) {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 使用downstream中的容器工厂。
*/
Supplier<A> supplier = downstream.supplier();
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 使用downstream中的择取操作。
*/
BiConsumer<A, T> accumulator = downstream.accumulator();
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 使用downstream中的合并操作。
*/
BinaryOperator<A> combiner = downstream.combiner();
/*
* 4.收尾操作(可选,最后执行)。
* 使用downstream中的收尾操作之后,还要再使用另一个收尾操作。
*/
Function<A, RR> finisher = downstream.finisher().andThen(thenFinisher);
/*
* 5.容器参数,指示容器的特征。
* 使用downstream中的容器参数;如果容器参数中包含IDENTITY_FINISH,则需要移除IDENTITY_FINISH的限制。
*/
Set<Characteristics> characteristics = downstream.characteristics();
// 如果downstream包含了IDENTITY_FINISH参数,则移除它
if(characteristics.contains(Characteristics.IDENTITY_FINISH)) {
if(characteristics.size() == 1) {
characteristics = Collectors.CH_NOID;
} else {
characteristics = EnumSet.copyOf(characteristics);
characteristics.remove(Characteristics.IDENTITY_FINISH);
characteristics = Collections.unmodifiableSet(characteristics);
}
}
return new CollectorImpl<>(supplier, accumulator, combiner, finisher, characteristics);
}
/*▲ 后处理 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 计数 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a {@code Collector} accepting elements of type {@code T} that
* counts the number of input elements. If no elements are present, the
* result is 0.
*
* @param <T> the type of the input elements
*
* @return a {@code Collector} that counts the input elements
*
* @implSpec This produces a result equivalent to:
* <pre>{@code
* reducing(0L, e -> 1L, Long::sum)
* }</pre>
*/
// 计数
public static <T> Collector<T, ?, Long> counting() {
return summingLong(e -> 1L);
}
/**
* Returns a {@code Collector} that produces the sum of a integer-valued
* function applied to the input elements. If no elements are present,
* the result is 0.
*
* @param <T> the type of the input elements
* @param mapper a function extracting the property to be summed
*
* @return a {@code Collector} that produces the sum of a derived property
*/
// 对一系列int元素求和,待求和元素需要先经过mapper的处理
public static <T> Collector<T, ?, Integer> summingInt(ToIntFunction<? super T> mapper) {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 使用int数组。
*/
Supplier<int[]> supplier = () -> new int[1];
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 将遇到的元素转换为int类型的值,然后累加起来。
*/
BiConsumer<int[], T> accumulator = (array, e) -> { array[0] += mapper.applyAsInt(e); };
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 将后一个容器中的和值累加到前一个容器的和值上,并返回前一个容器。
*/
BinaryOperator<int[]> combiner = (a, array2) -> {
a[0] += array2[0];
return a;
};
/*
* 4.收尾操作(可选,最后执行)。
* 返回获取到的和。
*/
Function<int[], Integer> finisher = array -> array[0];
/*
* 5.容器参数,指示容器的特征。
* 未设置任何参数。
*/
Set<Characteristics> characteristics = CH_NOID;
return new CollectorImpl<>(supplier, accumulator, combiner, characteristics);
}
/**
* Returns a {@code Collector} that produces the sum of a long-valued
* function applied to the input elements. If no elements are present,
* the result is 0.
*
* @param <T> the type of the input elements
* @param mapper a function extracting the property to be summed
*
* @return a {@code Collector} that produces the sum of a derived property
*/
// 对一系列long元素求和,待求和元素需要先经过mapper的处理
public static <T> Collector<T, ?, Long> summingLong(ToLongFunction<? super T> mapper) {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 使用long数组。
*/
Supplier<long[]> supplier = () -> new long[1];
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 将遇到的元素转换为long类型的值,然后累加起来。
*/
BiConsumer<long[], T> accumulator = (array, e) -> { array[0] += mapper.applyAsLong(e); };
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 将后一个容器中的和值累加到前一个容器的和值上,并返回前一个容器。
*/
BinaryOperator<long[]> combiner = (a, b) -> {
a[0] += b[0];
return a;
};
/*
* 4.收尾操作(可选,最后执行)。
* 返回获取到的和。
*/
Function<long[], Long> finisher = array -> array[0];
/*
* 5.容器参数,指示容器的特征。
* 未设置任何参数。
*/
Set<Characteristics> characteristics = CH_NOID;
return new CollectorImpl<>(supplier, accumulator, combiner, finisher, characteristics);
}
/**
* Returns a {@code Collector} that produces the sum of a double-valued
* function applied to the input elements. If no elements are present,
* the result is 0.
*
* <p>The sum returned can vary depending upon the order in which
* values are recorded, due to accumulated rounding error in
* addition of values of differing magnitudes. Values sorted by increasing
* absolute magnitude tend to yield more accurate results. If any recorded
* value is a {@code NaN} or the sum is at any point a {@code NaN} then the
* sum will be {@code NaN}.
*
* @param <T> the type of the input elements
* @param mapper a function extracting the property to be summed
*
* @return a {@code Collector} that produces the sum of a derived property
*/
// 对一系列double元素求和,待求和元素需要先经过mapper的处理
public static <T> Collector<T, ?, Double> summingDouble(ToDoubleFunction<? super T> mapper) {
/*
* 1.容器工厂(该工厂用来构造收纳元素的容器)。
* 使用double数组。
*/
Supplier<double[]> supplier = () -> new double[3];
/*
* 2.择取元素(这是(子)任务中的择取操作,通常用于将元素添加到目标容器)。
* 将遇到的元素转换为double类型的值,然后累加起来。
*/
BiConsumer<double[], T> accumulator = (array, e) -> {
double val = mapper.applyAsDouble(e);
sumWithCompensation(array, val);
array[2] += val;
};
/*
* 3.合并容器(这是合并操作,通常用于在并行流中合并子任务)。
* 将后一个容器中的和值累加到前一个容器的和值上,并返回前一个容器。
*/
BinaryOperator<double[]> combiner = (a, b) -> {
sumWithCompensation(a, b[0]);
a[2] += b[2];
return sumWithCompensation(a, b[1]);
};
/*
* 4.收尾操作(可选,最后执行)。
* 返回获取到的和。
*/
Function<double[], Double> finisher = array -> computeFinalSum(array);
/*
* 5.容器参数,指示容器的特征。
* 未设置任何参数。
*/
Set<Characteristics> characteristics = CH_NOID;
/*
* In the arrays allocated for the collect operation, index 0
* holds the high-order bits of the running sum, index 1 holds
* the low-order bits of the sum computed via compensated