-
Notifications
You must be signed in to change notification settings - Fork 246
/
StreamEx.java
3014 lines (2898 loc) · 122 KB
/
StreamEx.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 2015, 2016 Tagir Valeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package one.util.streamex;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.lang.reflect.Array;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.SortedMap;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
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.UnaryOperator;
import java.util.regex.Pattern;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.Collector.Characteristics;
import one.util.streamex.PairSpliterator.PSOfRef;
import static one.util.streamex.StreamExInternals.*;
/**
* A {@link Stream} implementation with additional functionality.
*
* <p>
* While {@code StreamEx} implements {@code Iterable}, it is not a
* general-purpose {@code Iterable} as it supports only a single
* {@code Iterator}; invoking the {@link #iterator iterator} method to obtain a
* second or subsequent iterator throws {@code IllegalStateException}.
*
* @author Tagir Valeev
*
* @param <T> the type of the stream elements
*/
public class StreamEx<T> extends AbstractStreamEx<T, StreamEx<T>> {
StreamEx(Stream<? extends T> stream, StreamContext context) {
super(stream, context);
}
StreamEx(Spliterator<? extends T> spliterator, StreamContext context) {
super(spliterator, context);
}
@Override
StreamEx<T> supply(Stream<T> stream) {
return new StreamEx<>(stream, context);
}
@Override
StreamEx<T> supply(Spliterator<T> spliterator) {
return new StreamEx<>(spliterator, context);
}
final <R> StreamEx<R> collapseInternal(BiPredicate<? super T, ? super T> collapsible, Function<T, R> mapper,
BiFunction<R, T, R> accumulator, BinaryOperator<R> combiner) {
CollapseSpliterator<T, R> spliterator = new CollapseSpliterator<>(collapsible, mapper, accumulator, combiner,
spliterator());
return new StreamEx<>(spliterator, context);
}
/**
* Returns a stream consisting of the elements of this stream which are
* instances of given class.
*
* <p>
* This is an <a href="package-summary.html#StreamOps">intermediate</a>
* operation.
*
* @param <TT> a type of instances to select.
* @param clazz a class which instances should be selected
* @return the new stream
*/
@SuppressWarnings("unchecked")
public <TT> StreamEx<TT> select(Class<TT> clazz) {
return (StreamEx<TT>) filter(clazz::isInstance);
}
/**
* Returns an {@link EntryStream} consisting of the {@link Entry} objects
* which keys are elements of this stream and values are results of applying
* the given function to the elements of this stream.
*
* <p>
* This is an <a href="package-summary.html#StreamOps">intermediate</a>
* operation.
*
* @param <V> The {@code Entry} value type
* @param valueMapper a non-interfering, stateless function to apply to each
* element
* @return the new stream
*/
public <V> EntryStream<T, V> mapToEntry(Function<? super T, ? extends V> valueMapper) {
return new EntryStream<>(stream().map(e -> new SimpleImmutableEntry<>(e, valueMapper.apply(e))), context);
}
/**
* Returns an {@link EntryStream} consisting of the {@link Entry} objects
* which keys and values are results of applying the given functions to the
* elements of this stream.
*
* <p>
* This is an <a href="package-summary.html#StreamOps">intermediate</a>
* operation.
*
* @param <K> The {@code Entry} key type
* @param <V> The {@code Entry} value type
* @param keyMapper a non-interfering, stateless function to apply to each
* element
* @param valueMapper a non-interfering, stateless function to apply to each
* element
* @return the new stream
*/
public <K, V> EntryStream<K, V> mapToEntry(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends V> valueMapper) {
return new EntryStream<>(stream()
.map(e -> new SimpleImmutableEntry<>(keyMapper.apply(e), valueMapper.apply(e))), context);
}
/**
* Returns a stream where the first element is the replaced with the result
* of applying the given function while the other elements are left intact.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">quasi-intermediate
* operation</a> with <a href="package-summary.html#TSO">tail-stream
* optimization</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 the first element
* @return the new stream
* @since 0.4.1
*/
public StreamEx<T> mapFirst(Function<? super T, ? extends T> mapper) {
return supply(new PairSpliterator.PSOfRef<>(mapper, spliterator(), true));
}
/**
* Returns a stream where the first element is transformed using
* {@code firstMapper} function and other elements are transformed using
* {@code notFirstMapper} function.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">quasi-intermediate
* operation</a>.
*
* @param <R> The element type of the new stream element
* @param firstMapper a <a
* href="package-summary.html#NonInterference">non-interfering </a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to the first element
* @param notFirstMapper a <a
* href="package-summary.html#NonInterference">non-interfering </a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to all elements except the first one.
* @return the new stream
* @since 0.6.0
* @see #mapFirst(Function)
*/
public <R> StreamEx<R> mapFirstOrElse(Function<? super T, ? extends R> firstMapper,
Function<? super T, ? extends R> notFirstMapper) {
return new StreamEx<>(new PairSpliterator.PSOfRef<>(firstMapper, notFirstMapper, spliterator(), true), context);
}
/**
* Returns a stream where the last element is the replaced with the result
* of applying the given function while the other elements are left intact.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">quasi-intermediate
* operation</a>.
*
* <p>
* The mapper function is called at most once. It could be not called at all
* if the stream is empty or there is short-circuiting operation downstream.
*
* @param mapper a <a
* href="package-summary.html#NonInterference">non-interfering </a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to the last element
* @return the new stream
* @since 0.4.1
*/
public StreamEx<T> mapLast(Function<? super T, ? extends T> mapper) {
return supply(new PairSpliterator.PSOfRef<>(mapper, spliterator(), false));
}
/**
* Returns a stream where the last element is transformed using
* {@code lastMapper} function and other elements are transformed using
* {@code notLastMapper} function.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">quasi-intermediate
* operation</a>.
*
* @param <R> The element type of the new stream element
* @param notLastMapper a <a
* href="package-summary.html#NonInterference">non-interfering </a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to all elements except the last one.
* @param lastMapper a <a
* href="package-summary.html#NonInterference">non-interfering </a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to the last element
* @return the new stream
* @since 0.6.0
* @see #mapFirst(Function)
*/
public <R> StreamEx<R> mapLastOrElse(Function<? super T, ? extends R> notLastMapper,
Function<? super T, ? extends R> lastMapper) {
return new StreamEx<>(new PairSpliterator.PSOfRef<>(lastMapper, notLastMapper, spliterator(), false), context);
}
/**
* Returns a stream consisting of the elements of this stream, additionally
* performing the provided action on the first stream element when it's
* consumed from the resulting stream.
*
* <p>
* This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* <p>
* The action is called at most once. For parallel stream pipelines, it's
* not guaranteed in which thread it will be executed, so if it modifies
* shared state, it is responsible for providing the required
* synchronization.
*
* <p>
* Note that the action might not be called at all if the first element is
* not consumed from the input (for example, if there's short-circuiting
* operation downstream which stopped the stream before the first element).
*
* <p>
* This method exists mainly to support debugging.
*
* @param action a <a href="package-summary.html#NonInterference">
* non-interfering</a> action to perform on the first stream element
* as it is consumed from the stream
* @return the new stream
* @since 0.6.0
*/
public StreamEx<T> peekFirst(Consumer<? super T> action) {
return mapFirst(x -> {
action.accept(x);
return x;
});
}
/**
* Returns a stream consisting of the elements of this stream, additionally
* performing the provided action on the last stream element when it's
* consumed from the resulting stream.
*
* <p>
* This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* <p>
* The action is called at most once. For parallel stream pipelines, it's
* not guaranteed in which thread it will be executed, so if it modifies
* shared state, it is responsible for providing the required
* synchronization.
*
* <p>
* Note that the action might not be called at all if the last element is
* not consumed from the input (for example, if there's short-circuiting
* operation downstream).
*
* <p>
* This method exists mainly to support debugging.
*
* @param action a <a href="package-summary.html#NonInterference">
* non-interfering</a> action to perform on the first stream element
* as it is consumed from the stream
* @return the new stream
* @since 0.6.0
*/
public StreamEx<T> peekLast(Consumer<? super T> action) {
return mapLast(x -> {
action.accept(x);
return x;
});
}
/**
* Creates a new {@code EntryStream} populated from entries of maps produced
* by supplied mapper function which is applied to the every element of this
* stream.
*
* <p>
* This is an <a href="package-summary.html#StreamOps">intermediate</a>
* operation.
*
* @param <K> the type of {@code Map} keys.
* @param <V> the type of {@code Map} values.
* @param mapper a non-interfering, stateless function to apply to each
* element which produces a {@link Map} of the entries corresponding
* to the single element of the current stream. The mapper function
* may return null or empty {@code Map} if no mapping should
* correspond to some element.
* @return the new {@code EntryStream}
*/
public <K, V> EntryStream<K, V> flatMapToEntry(Function<? super T, ? extends Map<K, V>> mapper) {
return new EntryStream<>(stream().flatMap(e -> {
Map<K, V> s = mapper.apply(e);
return s == null ? null : s.entrySet().stream();
}), context);
}
/**
* Performs a cross product of current stream with specified array of
* elements. As a result the {@link EntryStream} is created whose keys are
* elements of current stream and values are elements of the specified
* array.
*
* <p>
* The resulting stream contains all the possible combinations of keys and
* values.
*
* <p>
* This is an <a href="package-summary.html#StreamOps">intermediate</a>
* operation.
*
* @param <V> the type of array elements
* @param other the array to perform a cross product with
* @return the new {@code EntryStream}
* @throws NullPointerException if other is null
* @since 0.2.3
*/
@SuppressWarnings("unchecked")
public <V> EntryStream<T, V> cross(V... other) {
if (other.length == 0)
return new EntryStream<>(Spliterators.emptySpliterator(), context);
if (other.length == 1)
return mapToEntry(e -> other[0]);
return cross(t -> of(other));
}
/**
* Performs a cross product of current stream with specified
* {@link Collection} of elements. As a result the {@link EntryStream} is
* created whose keys are elements of current stream and values are elements
* of the specified collection.
*
* <p>
* The resulting stream contains all the possible combinations of keys and
* values.
*
* <p>
* This is an <a href="package-summary.html#StreamOps">intermediate</a>
* operation.
*
* @param <V> the type of collection elements
* @param other the collection to perform a cross product with
* @return the new {@code EntryStream}
* @throws NullPointerException if other is null
* @since 0.2.3
*/
public <V> EntryStream<T, V> cross(Collection<? extends V> other) {
if (other.isEmpty())
return new EntryStream<>(Spliterators.emptySpliterator(), context);
return cross(t -> of(other));
}
/**
* Creates a new {@code EntryStream} whose keys are elements of current
* stream and corresponding values are supplied by given function. 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</a>
* operation.
*
* @param <V> the type of values.
* @param mapper a non-interfering, stateless function to apply to each
* element which produces a stream of the values corresponding to the
* single element of the current stream.
* @return the new {@code EntryStream}
* @since 0.2.3
*/
public <V> EntryStream<T, V> cross(Function<? super T, ? extends Stream<? extends V>> mapper) {
return new EntryStream<>(stream().flatMap(a -> EntryStream.withKey(a, mapper.apply(a))), context);
}
/**
* Returns a {@code Map} whose keys are the values resulting from applying
* the classification function to the input elements, and whose
* corresponding values are {@code List}s containing the input elements
* which map to the associated key under the classification function.
*
* <p>
* There are no guarantees on the type, mutability or serializability of the
* {@code Map} or {@code List} objects returned.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* @param <K> the type of the keys
* @param classifier the classifier function mapping input elements to keys
* @return a {@code Map} containing the results of the group-by operation
*
* @see #groupingBy(Function, Collector)
* @see Collectors#groupingBy(Function)
* @see Collectors#groupingByConcurrent(Function)
*/
public <K> Map<K, List<T>> groupingBy(Function<? super T, ? extends K> classifier) {
return groupingBy(classifier, Collectors.toList());
}
/**
* Returns a {@code Map} whose keys are the values resulting from applying
* the classification function to the input elements, and whose
* corresponding values are the result of reduction of the input elements
* which map to the associated key under the classification function.
*
* <p>
* There are no guarantees on the type, mutability or serializability of the
* {@code Map} objects returned.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* @param <K> the type of the keys
* @param <D> the result type of the downstream reduction
* @param classifier the classifier function mapping input elements to keys
* @param downstream a {@code Collector} implementing the downstream
* reduction
* @return a {@code Map} containing the results of the group-by operation
*
* @see #groupingBy(Function)
* @see Collectors#groupingBy(Function, Collector)
* @see Collectors#groupingByConcurrent(Function, Collector)
*/
public <K, D> Map<K, D> groupingBy(Function<? super T, ? extends K> classifier,
Collector<? super T, ?, D> downstream) {
if (isParallel() && downstream.characteristics().contains(Characteristics.UNORDERED))
return rawCollect(Collectors.groupingByConcurrent(classifier, downstream));
return rawCollect(Collectors.groupingBy(classifier, downstream));
}
/**
* Returns a {@code Map} whose keys are the values resulting from applying
* the classification function to the input elements, and whose
* corresponding values are the result of reduction of the input elements
* which map to the associated key under the classification function.
*
* <p>
* The {@code Map} will be created using the provided factory function.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* @param <K> the type of the keys
* @param <D> the result type of the downstream reduction
* @param <M> the type of the resulting {@code Map}
* @param classifier the classifier function mapping input elements to keys
* @param mapFactory a function which, when called, produces a new empty
* {@code Map} of the desired type
* @param downstream a {@code Collector} implementing the downstream
* reduction
* @return a {@code Map} containing the results of the group-by operation
*
* @see #groupingBy(Function)
* @see Collectors#groupingBy(Function, Supplier, Collector)
* @see Collectors#groupingByConcurrent(Function, Supplier, Collector)
*/
@SuppressWarnings("unchecked")
public <K, D, M extends Map<K, D>> M groupingBy(Function<? super T, ? extends K> classifier,
Supplier<M> mapFactory, Collector<? super T, ?, D> downstream) {
if (isParallel() && downstream.characteristics().contains(Characteristics.UNORDERED)
&& mapFactory.get() instanceof ConcurrentMap)
return (M) rawCollect(Collectors.groupingByConcurrent(classifier,
(Supplier<ConcurrentMap<K, D>>) mapFactory, downstream));
return rawCollect(Collectors.groupingBy(classifier, mapFactory, downstream));
}
/**
* Returns a {@code Map} whose keys are the values resulting from applying
* the classification function to the input elements, and whose
* corresponding values are the collections of the input elements which map
* to the associated key under the classification function.
*
* <p>
* There are no guarantees on the type, mutability or serializability of the
* {@code Map} objects returned.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* @param <K> the type of the keys
* @param <C> the type of the collection used in resulting {@code Map}
* values
* @param classifier the classifier function mapping input elements to keys
* @param collectionFactory a function which returns a new empty
* {@code Collection} which will be used to store the stream
* elements.
* @return a {@code Map} containing the results of the group-by operation
*
* @see #groupingBy(Function, Collector)
* @see Collectors#groupingBy(Function, Collector)
* @see Collectors#groupingByConcurrent(Function, Collector)
* @since 0.2.2
*/
public <K, C extends Collection<T>> Map<K, C> groupingTo(Function<? super T, ? extends K> classifier,
Supplier<C> collectionFactory) {
return groupingBy(classifier, Collectors.toCollection(collectionFactory));
}
/**
* Returns a {@code Map} whose keys are the values resulting from applying
* the classification function to the input elements, and whose
* corresponding values are the collections of the input elements which map
* to the associated key under the classification function.
*
* <p>
* The {@code Map} will be created using the provided factory function.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* @param <K> the type of the keys
* @param <C> the type of the collection used in resulting {@code Map}
* values
* @param <M> the type of the resulting {@code Map}
* @param classifier the classifier function mapping input elements to keys
* @param mapFactory a function which, when called, produces a new empty
* {@code Map} of the desired type
* @param collectionFactory a function which returns a new empty
* {@code Collection} which will be used to store the stream
* elements.
* @return a {@code Map} containing the results of the group-by operation
*
* @see #groupingTo(Function, Supplier)
* @see Collectors#groupingBy(Function, Supplier, Collector)
* @see Collectors#groupingByConcurrent(Function, Supplier, Collector)
* @since 0.2.2
*/
public <K, C extends Collection<T>, M extends Map<K, C>> M groupingTo(Function<? super T, ? extends K> classifier,
Supplier<M> mapFactory, Supplier<C> collectionFactory) {
return groupingBy(classifier, mapFactory, Collectors.toCollection(collectionFactory));
}
/**
* Returns a {@code Map<Boolean, List<T>>} which contains two partitions of
* the input elements according to a {@code Predicate}.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code Map} returned.
*
* @param predicate a predicate used for classifying input elements
* @return a {@code Map<Boolean, List<T>>} which {@link Boolean#TRUE} key is
* mapped to the list of the stream elements for which predicate is
* true and {@link Boolean#FALSE} key is mapped to the list of all
* other stream elements.
*
* @see #partitioningBy(Predicate, Collector)
* @see Collectors#partitioningBy(Predicate)
* @since 0.2.2
*/
public Map<Boolean, List<T>> partitioningBy(Predicate<? super T> predicate) {
return collect(Collectors.partitioningBy(predicate));
}
/**
* Returns a {@code Map<Boolean, D>} which contains two partitions of the
* input elements according to a {@code Predicate}, which are reduced
* according to the supplied {@code Collector}.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation. The operation may short-circuit if the downstream collector is
* <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting</a>.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code Map} returned.
*
* @param <D> the result type of the downstream reduction
* @param predicate a predicate used for classifying input elements
* @param downstream a {@code Collector} implementing the downstream
* reduction
* @return a {@code Map<Boolean, List<T>>} which {@link Boolean#TRUE} key is
* mapped to the result of downstream {@code Collector} collecting
* the the stream elements for which predicate is true and
* {@link Boolean#FALSE} key is mapped to the result of downstream
* {@code Collector} collecting the other stream elements.
*
* @see #partitioningBy(Predicate)
* @see Collectors#partitioningBy(Predicate, Collector)
* @since 0.2.2
*/
public <D> Map<Boolean, D> partitioningBy(Predicate<? super T> predicate, Collector<? super T, ?, D> downstream) {
return collect(MoreCollectors.partitioningBy(predicate, downstream));
}
/**
* Returns a {@code Map<Boolean, C>} which contains two partitions of the
* input elements according to a {@code Predicate}.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code Map} returned.
*
* @param <C> the type of {@code Collection} used as returned {@code Map}
* values.
* @param predicate a predicate used for classifying input elements
* @param collectionFactory a function which returns a new empty
* {@code Collection} which will be used to store the stream
* elements.
* @return a {@code Map<Boolean, C>} which {@link Boolean#TRUE} key is
* mapped to the collection of the stream elements for which
* predicate is true and {@link Boolean#FALSE} key is mapped to the
* collection of all other stream elements.
*
* @see #partitioningBy(Predicate, Collector)
* @see Collectors#partitioningBy(Predicate)
* @since 0.2.2
*/
public <C extends Collection<T>> Map<Boolean, C> partitioningTo(Predicate<? super T> predicate,
Supplier<C> collectionFactory) {
return collect(Collectors.partitioningBy(predicate, Collectors.toCollection(collectionFactory)));
}
/**
* Returns a {@link String} which is the concatenation of the results
* of calling {@link String#valueOf(Object)} on each element of this stream
* in encounter order.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* @return the result of concatenation. For empty input stream empty String
* is returned.
*/
public String joining() {
return map(String::valueOf).rawCollect(Collectors.joining());
}
/**
* Returns a {@link String} which is the concatenation of the results
* of calling {@link String#valueOf(Object)} on each element of this stream,
* separated by the specified delimiter, in encounter order.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* @param delimiter the delimiter to be used between each element
* @return the result of concatenation. For empty input stream empty String
* is returned.
*/
public String joining(CharSequence delimiter) {
return map(String::valueOf).rawCollect(Collectors.joining(delimiter));
}
/**
* Returns a {@link String} which is the concatenation of the results
* of calling {@link String#valueOf(Object)} on each element of this stream,
* separated by the specified delimiter, with the specified prefix and
* suffix in encounter order.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* @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 the result of concatenation. For empty input stream
* {@code prefix + suffix} is returned.
*/
public String joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) {
return map(String::valueOf).rawCollect(Collectors.joining(delimiter, prefix, suffix));
}
/**
* Returns an array containing all the stream elements using the supplied
* element type class to allocate an array.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* @param <A> the element type of the resulting array
* @param elementClass the type of array elements
* @return an array containing the elements in this stream
* @throws ArrayStoreException if the runtime type of the array returned
* from the array generator is not a supertype of the runtime type
* of every element in this stream
* @see #toArray(java.util.function.IntFunction)
* @since 0.6.3
*/
@SuppressWarnings("unchecked")
public <A> A[] toArray(Class<A> elementClass) {
return stream().toArray(size -> (A[])Array.newInstance(elementClass, size));
}
/**
* Returns an array containing all the stream elements. If the stream
* happens to contain no elements, the supplied empty array is returned
* instead. Otherwise the new array is allocated which element type is the
* same as the element type of supplied empty array.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* <p>
* This method is useful when the stream is expected to return empty arrays
* often, so the same instance of empty array (presumably declared in some
* static final field) can be reused.
*
* @param <A> the element type of the resulting array
* @param emptyArray an empty array of the resulting type
* @return an array containing the elements in this stream or the passed
* empty array if the stream is empty
* @throws ArrayStoreException if the runtime type of the array returned
* from the array generator is not a supertype of the runtime type
* of every element in this stream
* @see #toArray(java.util.function.IntFunction)
* @since 0.6.3
*/
@SuppressWarnings("unchecked")
public <A> A[] toArray(A[] emptyArray) {
if(emptyArray.length != 0) {
throw new IllegalArgumentException("Empty array must be supplied");
}
return stream().toArray(size -> size == 0 ? emptyArray
: (A[]) Array.newInstance(emptyArray.getClass().getComponentType(), size));
}
/**
* Returns a collection created by provided supplier function which contains
* all the elements of the collections generated by provided mapper from
* each element of this stream.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* <p>
* This method is equivalent to
* {@code flatCollection(mapper).toCollection(supplier)}, but may work
* faster.
*
* @param <U> the type of the elements of the resulting collection
* @param <C> the type of the resulting collection
* @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
* {@link Collection} of new values
* @param supplier a supplier for the resulting collection
* @return the new collection.
* @since 0.3.7
*/
public <U, C extends Collection<U>> C toFlatCollection(Function<? super T, ? extends Collection<U>> mapper,
Supplier<C> supplier) {
return map(mapper).collect(supplier, Collection::addAll, Collection::addAll);
}
/**
* Returns a {@link List} which contains all the elements of the collections
* generated by provided mapper from each element of this stream. 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 #toFlatCollection(Function, Supplier)}.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* <p>
* This method is equivalent to {@code flatCollection(mapper).toList()}, but
* may work faster.
*
* @param <U> the type of the elements of the resulting collection
* @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
* {@link Collection} of new values
* @return the new list.
* @since 0.3.7
*/
public <U> List<U> toFlatList(Function<? super T, ? extends Collection<U>> mapper) {
return toFlatCollection(mapper, ArrayList::new);
}
/**
* Returns a {@link Map} whose keys are elements from this stream and values
* are the result of applying the provided mapping functions to the input
* elements.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* <p>
* Returned {@code Map} is guaranteed to be modifiable.
*
* <p>
* For parallel stream the concurrent {@code Map} is created.
*
* @param <V> the output type of the value mapping function
* @param valMapper a mapping function to produce values
* @return a {@code Map} whose keys are elements from this stream and values
* are the result of applying mapping function to the input elements
* @throws IllegalStateException if this stream contains duplicate objects
* (according to {@link Object#equals(Object)})
* @see Collectors#toMap(Function, Function)
* @see Collectors#toConcurrentMap(Function, Function)
* @see #toMap(Function, Function)
*/
public <V> Map<T, V> toMap(Function<? super T, ? extends V> valMapper) {
return toMap(Function.identity(), valMapper);
}
/**
* Returns a {@link Map} whose keys and values are the result of applying
* the provided mapping functions to the input elements.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* <p>
* Returned {@code Map} is guaranteed to be modifiable.
*
* <p>
* For parallel stream the concurrent {@code Map} is created.
*
* @param <K> the output type of the key mapping function
* @param <V> the output type of the value mapping function
* @param keyMapper a mapping function to produce keys
* @param valMapper a mapping function to produce values
* @return a {@code Map} whose keys and values are the result of applying
* mapping functions to the input elements
* @throws IllegalStateException if duplicate mapped key is found (according
* to {@link Object#equals(Object)})
*
* @see Collectors#toMap(Function, Function)
* @see Collectors#toConcurrentMap(Function, Function)
* @see #toMap(Function)
*/
public <K, V> Map<K, V> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valMapper) {
Map<K, V> map = isParallel() ? new ConcurrentHashMap<>() : new HashMap<>();
return toMapThrowing(keyMapper, valMapper, map);
}
/**
* Returns a {@link Map} whose keys and values are the result of applying
* the provided mapping functions to the input elements.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* <p>
* If the mapped keys contains duplicates (according to
* {@link Object#equals(Object)}), the value mapping function is applied to
* each equal element, and the results are merged using the provided merging
* function.
*
* <p>
* Returned {@code Map} is guaranteed to be modifiable.
*
* @param <K> the output type of the key mapping function
* @param <V> the output type of the value mapping function
* @param keyMapper a mapping function to produce keys
* @param valMapper a mapping function to produce values
* @param mergeFunction a merge function, used to resolve collisions between
* values associated with the same key, as supplied to
* {@link Map#merge(Object, Object, BiFunction)}
* @return a {@code Map} whose keys are the result of applying a key mapping
* function to the input elements, and whose values are the result
* of applying a value mapping function to all input elements equal
* to the key and combining them using the merge function
*
* @see Collectors#toMap(Function, Function, BinaryOperator)
* @see Collectors#toConcurrentMap(Function, Function, BinaryOperator)
* @see #toMap(Function, Function)
* @since 0.1.0
*/
public <K, V> Map<K, V> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends V> valMapper, BinaryOperator<V> mergeFunction) {
return rawCollect(Collectors.toMap(keyMapper, valMapper, mergeFunction, HashMap::new));
}
/**
* Returns a {@link SortedMap} whose keys are elements from this stream and
* values are the result of applying the provided mapping functions to the
* input elements.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>
* operation.
*
* <p>
* If this stream contains duplicates (according to
* {@link Object#equals(Object)}), an {@code IllegalStateException} is
* thrown when the collection operation is performed.
*
* <p>
* For parallel stream the concurrent {@code SortedMap} is created.
*
* <p>
* Returned {@code SortedMap} is guaranteed to be modifiable.
*
* @param <V> the output type of the value mapping function
* @param valMapper a mapping function to produce values
* @return a {@code SortedMap} whose keys are elements from this stream and
* values are the result of applying mapping function to the input
* elements
*
* @see Collectors#toMap(Function, Function)
* @see Collectors#toConcurrentMap(Function, Function)
* @see #toSortedMap(Function, Function)
* @since 0.1.0
*/
public <V> SortedMap<T, V> toSortedMap(Function<? super T, ? extends V> valMapper) {
return toSortedMap(Function.identity(), valMapper);
}
/**
* Returns a {@link SortedMap} whose keys and values are the result of
* applying the provided mapping functions to the input elements.
*
* <p>
* This is a <a href="package-summary.html#StreamOps">terminal</a>