-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path121.java
More file actions
2697 lines (2532 loc) · 97 KB
/
Copy path121.java
File metadata and controls
2697 lines (2532 loc) · 97 KB
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, 2017 StreamEx contributors
*
* 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.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.Buffer;
import java.util.*;
import java.util.Map.Entry;
import java.util.PrimitiveIterator.OfInt;
import java.util.Spliterators.AbstractIntSpliterator;
import java.util.concurrent.ForkJoinPool;
import java.util.function.*;
import java.util.stream.*;
import static one.util.streamex.StreamExInternals.*;
/**
* An {@link IntStream} implementation with additional functionality
*
* @author Tagir Valeev
*/
public class IntStreamEx extends BaseStreamEx<Integer, IntStream, Spliterator.OfInt, IntStreamEx> implements IntStream {
IntStreamEx(IntStream stream, StreamContext context) {
super(stream, context);
}
IntStreamEx(Spliterator.OfInt spliterator, StreamContext context) {
super(spliterator, context);
}
@Override
IntStream createStream() {
return StreamSupport.intStream(spliterator, context.parallel);
}
private static IntStreamEx seq(IntStream stream) {
return new IntStreamEx(stream, StreamContext.SEQUENTIAL);
}
final IntStreamEx delegate(Spliterator.OfInt spliterator) {
return new IntStreamEx(spliterator, context);
}
private <A> A collectSized(Supplier<A> supplier, ObjIntConsumer<A> accumulator, BiConsumer<A, A> combiner,
IntFunction<A> sizedSupplier, ObjIntConsumer<A> sizedAccumulator) {
if (isParallel())
return collect(supplier, accumulator, combiner);
java.util.Spliterator.OfInt spliterator = spliterator();
long size = spliterator.getExactSizeIfKnown();
A intermediate;
if (size >= 0 && size <= Integer.MAX_VALUE) {
intermediate = sizedSupplier.apply((int) size);
spliterator.forEachRemaining((IntConsumer) i -> sizedAccumulator.accept(intermediate, i));
} else {
intermediate = supplier.get();
spliterator.forEachRemaining((IntConsumer) i -> accumulator.accept(intermediate, i));
}
return intermediate;
}
@Override
public IntStreamEx unordered() {
return (IntStreamEx) super.unordered();
}
@Override
public IntStreamEx onClose(Runnable closeHandler) {
return (IntStreamEx) super.onClose(closeHandler);
}
@Override
public IntStreamEx filter(IntPredicate predicate) {
return new IntStreamEx(stream().filter(predicate), context);
}
/**
* Returns a stream consisting of the elements of this stream that don't
* match the given predicate.
*
* <p>
* This is an intermediate operation.
*
* @param predicate a non-interfering, stateless predicate to apply to each
* element to determine if it should be excluded
* @return the new stream
*/
public IntStreamEx remove(IntPredicate predicate) {
return filter(predicate.negate());
}
/**
* Returns true if this stream contains the specified value.
*
* <p>
* This is a short-circuiting terminal operation.
*
* @param value the value too look for in the stream
* @return true if this stream contains the specified value
* @see IntStream#anyMatch(IntPredicate)
*/
public boolean has(int value) {
return anyMatch(x -> x == value);
}
/**
* Returns a stream consisting of the elements of this stream that don't
* equal to the given value.
*
* <p>
* This is an intermediate operation.
*
* @param value the value to remove from the stream.
* @return the new stream
* @since 0.2.2
* @see #without(int...)
* @see #remove(IntPredicate)
*/
public IntStreamEx without(int value) {
return filter(val -> val != value);
}
/**
* Returns a stream consisting of the elements of this stream that don't
* equal to any of the supplied values.
*
* <p>
* This is an <a href="package-summary.html#StreamOps">intermediate</a>
* operation. May return itself if no values were supplied.
*
* <p>
* Current implementation scans the supplied values linearly for every
* stream element.
*
* <p>
* If the {@code values} array is changed between calling this method and
* finishing the stream traversal, then the result of the stream traversal
* is undefined: changes may or may not be taken into account.
*
* @param values the values to remove from the stream.
* @return the new stream
* @since 0.5.5
* @see #without(int)
* @see #remove(IntPredicate)
*/
public IntStreamEx without(int... values) {
if (values.length == 0)
return this;
if (values.length == 1)
return without(values[0]);
return filter(x -> {
for (int val : values) {
if (x == val)
return false;
}
return true;
});
}
/**
* Returns a stream consisting of the elements of this stream that strictly
* greater than the specified value.
*
* <p>
* This is an intermediate operation.
*
* @param value a value to compare to
* @return the new stream
* @since 0.2.3
*/
public IntStreamEx greater(int value) {
return filter(val -> val > value);
}
/**
* Returns a stream consisting of the elements of this stream that greater
* than or equal to the specified value.
*
* <p>
* This is an intermediate operation.
*
* @param value a value to compare to
* @return the new stream
* @since 0.2.3
*/
public IntStreamEx atLeast(int value) {
return filter(val -> val >= value);
}
/**
* Returns a stream consisting of the elements of this stream that strictly
* less than the specified value.
*
* <p>
* This is an intermediate operation.
*
* @param value a value to compare to
* @return the new stream
* @since 0.2.3
*/
public IntStreamEx less(int value) {
return filter(val -> val < value);
}
/**
* Returns a stream consisting of the elements of this stream that less than
* or equal to the specified value.
*
* <p>
* This is an intermediate operation.
*
* @param value a value to compare to
* @return the new stream
* @since 0.2.3
*/
public IntStreamEx atMost(int value) {
return filter(val -> val <= value);
}
@Override
public IntStreamEx map(IntUnaryOperator mapper) {
return new IntStreamEx(stream().map(mapper), context);
}
@Override
public <U> StreamEx<U> mapToObj(IntFunction<? extends U> mapper) {
return new StreamEx<>(stream().mapToObj(mapper), context);
}
@Override
public LongStreamEx mapToLong(IntToLongFunction mapper) {
return new LongStreamEx(stream().mapToLong(mapper), context);
}
@Override
public DoubleStreamEx mapToDouble(IntToDoubleFunction mapper) {
return new DoubleStreamEx(stream().mapToDouble(mapper), 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 intermediate 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
* @since 0.3.1
*/
public <K, V> EntryStream<K, V> mapToEntry(IntFunction<? extends K> keyMapper,
IntFunction<? extends V> valueMapper) {
return new EntryStream<>(stream().mapToObj(t -> new AbstractMap.SimpleImmutableEntry<>(keyMapper.apply(t),
valueMapper.apply(t))), context);
}
@Override
public IntStreamEx flatMap(IntFunction<? extends IntStream> mapper) {
return new IntStreamEx(stream().flatMap(mapper), context);
}
/**
* Returns a {@link LongStreamEx} 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 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 intermediate operation.
*
* @param mapper a non-interfering, stateless function to apply to each
* element which produces a {@code LongStream} of new values
* @return the new stream
* @since 0.3.0
*/
public LongStreamEx flatMapToLong(IntFunction<? extends LongStream> mapper) {
return new LongStreamEx(stream().mapToObj(mapper).flatMapToLong(Function.identity()), context);
}
/**
* Returns a {@link DoubleStreamEx} 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 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 intermediate operation.
*
* @param mapper a non-interfering, stateless function to apply to each
* element which produces a {@code DoubleStream} of new values
* @return the new stream
* @since 0.3.0
*/
public DoubleStreamEx flatMapToDouble(IntFunction<? extends DoubleStream> mapper) {
return new DoubleStreamEx(stream().mapToObj(mapper).flatMapToDouble(Function.identity()), context);
}
/**
* Returns a {@link StreamEx} 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 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 intermediate operation.
*
* @param <R> The element type of the new stream
* @param mapper a non-interfering, stateless function to apply to each
* element which produces a {@code Stream} of new values
* @return the new stream
* @since 0.3.0
*/
public <R> StreamEx<R> flatMapToObj(IntFunction<? extends Stream<R>> mapper) {
return new StreamEx<>(stream().mapToObj(mapper).flatMap(Function.identity()), context);
}
/**
* Returns a new stream containing all the elements of the original stream interspersed with
* given delimiter.
*
* <p>
* For example, {@code IntStreamEx.of(1, 2, 3).intersperse(4)} will yield a stream containing
* five elements: 1, 4, 2, 4, 3.
*
* <p>
* This is an <a href="package-summary.html#StreamOps">intermediate operation</a>.
*
* @param delimiter a delimiter to be inserted between each pair of elements
* @return the new stream
* @since 0.6.6
*/
public IntStreamEx intersperse(int delimiter) {
return new IntStreamEx(stream().flatMap(s -> IntStreamEx.of(delimiter, s)).skip(1), context);
}
@Override
public IntStreamEx distinct() {
return new IntStreamEx(stream().distinct(), context);
}
@Override
public IntStreamEx sorted() {
return new IntStreamEx(stream().sorted(), context);
}
/**
* Returns a stream consisting of the elements of this stream sorted
* according to the given comparator. Stream elements are boxed before
* passing to the 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
*/
public IntStreamEx sorted(Comparator<Integer> comparator) {
return new IntStreamEx(stream().boxed().sorted(comparator).mapToInt(Integer::intValue), context);
}
/**
* Returns a stream consisting of the elements of this stream in reverse
* sorted order.
*
* <p>
* This is a stateful intermediate operation.
*
* @return the new stream
* @since 0.0.8
*/
public IntStreamEx reverseSorted() {
IntUnaryOperator inv = x -> ~x;
return new IntStreamEx(stream().map(inv).sorted().map(inv), context);
}
/**
* Returns a stream consisting of the elements of this stream, sorted
* according to the natural order of the keys extracted by provided
* function.
*
* <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 <V> the type of the {@code Comparable} sort key
* @param keyExtractor a
* <a href="package-summary.html#NonInterference">non-interfering
* </a>, <a href="package-summary.html#Statelessness">stateless</a>
* function to be used to extract sorting keys
* @return the new stream
*/
public <V extends Comparable<? super V>> IntStreamEx sortedBy(IntFunction<V> keyExtractor) {
return sorted(Comparator.comparing(keyExtractor::apply));
}
/**
* Returns a stream consisting of the elements of this stream, sorted
* according to the int values extracted by provided function.
*
* <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 keyExtractor a
* <a href="package-summary.html#NonInterference">non-interfering
* </a>, <a href="package-summary.html#Statelessness">stateless</a>
* function to be used to extract sorting keys
* @return the new stream
*/
public IntStreamEx sortedByInt(IntUnaryOperator keyExtractor) {
return sorted(Comparator.comparingInt(keyExtractor::applyAsInt));
}
/**
* Returns a stream consisting of the elements of this stream, sorted
* according to the long values extracted by provided function.
*
* <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 keyExtractor a
* <a href="package-summary.html#NonInterference">non-interfering
* </a>, <a href="package-summary.html#Statelessness">stateless</a>
* function to be used to extract sorting keys
* @return the new stream
*/
public IntStreamEx sortedByLong(IntToLongFunction keyExtractor) {
return sorted(Comparator.comparingLong(keyExtractor::applyAsLong));
}
/**
* Returns a stream consisting of the elements of this stream, sorted
* according to the double values extracted by provided function.
*
* <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 keyExtractor a
* <a href="package-summary.html#NonInterference">non-interfering
* </a>, <a href="package-summary.html#Statelessness">stateless</a>
* function to be used to extract sorting keys
* @return the new stream
*/
public IntStreamEx sortedByDouble(IntToDoubleFunction keyExtractor) {
return sorted(Comparator.comparingDouble(keyExtractor::applyAsDouble));
}
@Override
public IntStreamEx peek(IntConsumer action) {
return new IntStreamEx(stream().peek(action), 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 IntStreamEx peekFirst(IntConsumer 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 IntStreamEx peekLast(IntConsumer action) {
return mapLast(x -> {
action.accept(x);
return x;
});
}
@Override
public IntStreamEx limit(long maxSize) {
return new IntStreamEx(stream().limit(maxSize), context);
}
@Override
public IntStreamEx skip(long n) {
return new IntStreamEx(stream().skip(n), context);
}
@Override
public void forEach(IntConsumer action) {
if (spliterator != null && !isParallel()) {
spliterator().forEachRemaining(action);
} else {
if (context.fjp != null)
context.terminate(() -> {
stream().forEach(action);
return null;
});
else {
stream().forEach(action);
}
}
}
@Override
public void forEachOrdered(IntConsumer action) {
if (spliterator != null && !isParallel()) {
spliterator().forEachRemaining(action);
} else {
if (context.fjp != null)
context.terminate(() -> {
stream().forEachOrdered(action);
return null;
});
else {
stream().forEachOrdered(action);
}
}
}
@Override
public int[] toArray() {
if (context.fjp != null)
return context.terminate(stream()::toArray);
return stream().toArray();
}
/**
* Returns a {@code byte[]} array containing the elements of this stream
* which are converted to bytes using {@code (byte)} cast operation.
*
* <p>
* This is a terminal operation.
*
* @return an array containing the elements of this stream
* @since 0.3.0
*/
public byte[] toByteArray() {
return collectSized(ByteBuffer::new, ByteBuffer::add, ByteBuffer::addAll, ByteBuffer::new,
ByteBuffer::addUnsafe).toArray();
}
/**
* Returns a {@code char[]} array containing the elements of this stream
* which are converted to chars using {@code (char)} cast operation.
*
* <p>
* This is a terminal operation.
*
* @return an array containing the elements of this stream
* @since 0.3.0
*/
public char[] toCharArray() {
return collectSized(CharBuffer::new, CharBuffer::add, CharBuffer::addAll, CharBuffer::new,
CharBuffer::addUnsafe).toArray();
}
/**
* Returns a {@code short[]} array containing the elements of this stream
* which are converted to shorts using {@code (short)} cast operation.
*
* <p>
* This is a terminal operation.
*
* @return an array containing the elements of this stream
* @since 0.3.0
*/
public short[] toShortArray() {
return collectSized(ShortBuffer::new, ShortBuffer::add, ShortBuffer::addAll, ShortBuffer::new,
ShortBuffer::addUnsafe).toArray();
}
/**
* Returns a {@link BitSet} containing the elements of this stream.
*
* <p>
* This is a terminal operation.
*
* @return a {@code BitSet} which set bits correspond to the elements of
* this stream.
* @since 0.2.0
*/
public BitSet toBitSet() {
return collect(BitSet::new, BitSet::set, BitSet::or);
}
/**
* Returns an {@code InputStream} lazily populated from the current
* {@code IntStreamEx}.
*
* <p>
* Note that only the least-significant byte of every number encountered in
* this stream is preserved in the resulting {@code InputStream}, other
* bytes are silently lost. Thus it's a caller responsibility to check
* whether this may cause problems.
*
* <p>
* This is a terminal operation.
*
* <p>
* When the resulting {@code InputStream} is closed, this
* {@code IntStreamEx} is closed as well.
*
* @return a new {@code InputStream}.
* @see #of(InputStream)
* @since 0.6.1
*/
public InputStream asByteInputStream() {
Spliterator.OfInt spltr = spliterator();
return new InputStream() {
private int last;
@Override
public int read() {
return spltr.tryAdvance((int val) -> last = val) ? (last & 0xFF) : -1;
}
@Override
public void close() {
IntStreamEx.this.close();
}
};
}
@Override
public int reduce(int identity, IntBinaryOperator op) {
if (context.fjp != null)
return context.terminate(() -> stream().reduce(identity, op));
return stream().reduce(identity, op);
}
@Override
public OptionalInt reduce(IntBinaryOperator op) {
if (context.fjp != null)
return context.terminate(op, stream()::reduce);
return stream().reduce(op);
}
/**
* Folds the elements of this stream using the provided accumulation
* function, going left to right. This is equivalent to:
*
* <pre>
* {@code
* boolean foundAny = false;
* int result = 0;
* for (int element : this stream) {
* if (!foundAny) {
* foundAny = true;
* result = element;
* }
* else
* result = accumulator.apply(result, element);
* }
* return foundAny ? OptionalInt.of(result) : OptionalInt.empty();
* }
* </pre>
*
* <p>
* This is a terminal operation.
*
* <p>
* This method cannot take all the advantages of parallel streams as it must
* process elements strictly left to right. If your accumulator function is
* associative, consider using {@link #reduce(IntBinaryOperator)} method.
*
* <p>
* For parallel stream it's not guaranteed that accumulator will always be
* executed in the same thread.
*
* @param accumulator a
* <a href="package-summary.html#NonInterference">non-interfering
* </a>, <a href="package-summary.html#Statelessness">stateless</a>
* function for incorporating an additional element into a result
* @return the result of the folding
* @see #foldLeft(int, IntBinaryOperator)
* @see #reduce(IntBinaryOperator)
* @since 0.4.0
*/
public OptionalInt foldLeft(IntBinaryOperator accumulator) {
PrimitiveBox b = new PrimitiveBox();
forEachOrdered(t -> {
if (b.b)
b.i = accumulator.applyAsInt(b.i, t);
else {
b.i = t;
b.b = true;
}
});
return b.asInt();
}
/**
* Folds the elements of this stream using the provided seed object and
* accumulation function, going left to right. This is equivalent to:
*
* <pre>
* {@code
* int result = seed;
* for (int element : this stream)
* result = accumulator.apply(result, element)
* return result;
* }
* </pre>
*
* <p>
* This is a terminal operation.
*
* <p>
* This method cannot take all the advantages of parallel streams as it must
* process elements strictly left to right. If your accumulator function is
* associative, consider using {@link #reduce(int, IntBinaryOperator)}
* method.
*
* <p>
* For parallel stream it's not guaranteed that accumulator will always be
* executed in the same thread.
*
* @param seed the starting value
* @param accumulator a
* <a href="package-summary.html#NonInterference">non-interfering
* </a>, <a href="package-summary.html#Statelessness">stateless</a>
* function for incorporating an additional element into a result
* @return the result of the folding
* @see #reduce(int, IntBinaryOperator)
* @see #foldLeft(IntBinaryOperator)
* @since 0.4.0
*/
public int foldLeft(int seed, IntBinaryOperator accumulator) {
int[] box = new int[] { seed };
forEachOrdered(t -> box[0] = accumulator.applyAsInt(box[0], t));
return box[0];
}
/**
* Produces an array containing cumulative results of applying the
* accumulation function going left to right.
*
* <p>
* This is a terminal operation.
*
* <p>
* For parallel stream it's not guaranteed that accumulator will always be
* executed in the same thread.
*
* <p>
* This method cannot take all the advantages of parallel streams as it must
* process elements strictly left to right.
*
* @param accumulator a
* <a href="package-summary.html#NonInterference">non-interfering
* </a>, <a href="package-summary.html#Statelessness">stateless</a>
* function for incorporating an additional element into a result
* @return the array where the first element is the first element of this
* stream and every successor element is the result of applying
* accumulator function to the previous array element and the
* corresponding stream element. The resulting array has the same
* length as this stream.
* @see #foldLeft(IntBinaryOperator)
* @since 0.5.1
*/
public int[] scanLeft(IntBinaryOperator accumulator) {
Spliterator.OfInt spliterator = spliterator();
long size = spliterator.getExactSizeIfKnown();
IntBuffer buf = new IntBuffer(size >= 0 && size <= Integer.MAX_VALUE ? (int) size : INITIAL_SIZE);
delegate(spliterator).forEachOrdered(i -> buf.add(buf.size == 0 ? i
: accumulator.applyAsInt(buf.data[buf.size - 1], i)));
return buf.toArray();
}
/**
* Produces an array containing cumulative results of applying the
* accumulation function going left to right using given seed value.
*
* <p>
* This is a terminal operation.
*
* <p>
* For parallel stream it's not guaranteed that accumulator will always be
* executed in the same thread.
*
* <p>
* This method cannot take all the advantages of parallel streams as it must
* process elements strictly left to right.
*
* @param seed the starting value
* @param accumulator a
* <a href="package-summary.html#NonInterference">non-interfering
* </a>, <a href="package-summary.html#Statelessness">stateless</a>
* function for incorporating an additional element into a result
* @return the array where the first element is the seed and every successor
* element is the result of applying accumulator function to the
* previous array element and the corresponding stream element. The
* resulting array is one element longer than this stream.
* @see #foldLeft(int, IntBinaryOperator)
* @since 0.5.1
*/
public int[] scanLeft(int seed, IntBinaryOperator accumulator) {
return prepend(seed).scanLeft(accumulator);
}
/**
* {@inheritDoc}
*
* @see #collect(IntCollector)
*/
@Override
public <R> R collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner) {
if (context.fjp != null)
return context.terminate(() -> stream().collect(supplier, accumulator, combiner));
return stream().collect(supplier, accumulator, combiner);
}
/**
* Performs a mutable reduction operation on the elements of this stream
* using an {@link IntCollector} which encapsulates the supplier,
* accumulator and merger functions making easier to reuse collection
* strategies.
*
* <p>
* Like {@link #reduce(int, IntBinaryOperator)}, {@code collect} operations
* can be parallelized without requiring additional synchronization.
*
* <p>
* This is a terminal operation.
*
* @param <A> the intermediate accumulation type of the {@code IntCollector}
* @param <R> type of the result
* @param collector the {@code IntCollector} describing the reduction
* @return the result of the reduction
* @see #collect(Supplier, ObjIntConsumer, BiConsumer)
* @since 0.3.0
*/
@SuppressWarnings("unchecked")
public <A, R> R collect(IntCollector<A, R> collector) {
if (collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH))
return (R) collect(collector.supplier(), collector.intAccumulator(), collector.merger());
return collector.finisher().apply(collect(collector.supplier(), collector.intAccumulator(), collector
.merger()));
}
@Override
public int sum() {
return reduce(0, Integer::sum);
}
@Override
public OptionalInt min() {
return reduce(Integer::min);
}
/**
* Returns the minimum element of this stream according to the provided
* {@code Comparator}.
*
* <p>
* This is a terminal operation.
*
* @param comparator a non-interfering, stateless {@link Comparator} to
* compare elements of this stream
* @return an {@code OptionalInt} describing the minimum element of this
* stream, or an empty {@code OptionalInt} if the stream is empty
* @since 0.1.2
*/
public OptionalInt min(Comparator<Integer> comparator) {
return reduce((a, b) -> comparator.compare(a, b) > 0 ? b : a);
}
/**
* Returns the minimum element of this stream according to the provided key
* extractor function.
*
* <p>
* This is a terminal operation.
*
* @param <V> the type of the {@code Comparable} sort key
* @param keyExtractor a non-interfering, stateless function
* @return an {@code OptionalInt} describing some element of this stream for
* which the lowest value was returned by key extractor, or an empty
* {@code OptionalInt} if the stream is empty
* @since 0.1.2
*/
public <V extends Comparable<? super V>> OptionalInt minBy(IntFunction<V> keyExtractor) {
ObjIntBox<V> result = collect(() -> new ObjIntBox<>(null, 0), (box, i) -> {
V val = Objects.requireNonNull(keyExtractor.apply(i));
if (box.a == null || box.a.compareTo(val) > 0) {
box.a = val;
box.b = i;
}
}, (box1, box2) -> {
if (box2.a != null && (box1.a == null || box1.a.compareTo(box2.a) > 0)) {
box1.a = box2.a;
box1.b = box2.b;
}
});
return result.a == null ? OptionalInt.empty() : OptionalInt.of(result.b);
}
/**
* Returns the minimum element of this stream according to the provided key
* extractor function.
*
* <p>