diff --git a/README.md b/README.md index a437cf8f..addea767 100644 --- a/README.md +++ b/README.md @@ -14,9 +14,9 @@ class as well as primitive collectors concept. Full API documentation is available [here](http://amaembo.github.io/streamex/javadoc/). -Take a look at the [Cheatsheet](CHEATSHEET.md) for brief introduction to the StreamEx! +Take a look at the [Cheatsheet](wiki/CHEATSHEET.md) for brief introduction to the StreamEx! -Before updating StreamEx check the [migration notes](MIGRATION.md) and full list of [changes](CHANGES.md). +Before updating StreamEx check the [migration notes](wiki/MIGRATION.md) and full list of [changes](wiki/CHANGES.md). StreamEx library main points are following: @@ -123,7 +123,7 @@ This project is licensed under [Apache License, version 2.0](https://www.apache. Releases are available in [Maven Central](https://repo1.maven.org/maven2/one/util/streamex/) -Before updating StreamEx check the [migration notes](MIGRATION.md) and full list of [changes](CHANGES.md). +Before updating StreamEx check the [migration notes](wiki/MIGRATION.md) and full list of [changes](wiki/CHANGES.md). #### Maven diff --git a/src/main/java-mr/9/one/util/streamex/Java9Specific.java b/src/main/java-mr/9/one/util/streamex/Java9Specific.java index d9377314..286780c0 100644 --- a/src/main/java-mr/9/one/util/streamex/Java9Specific.java +++ b/src/main/java-mr/9/one/util/streamex/Java9Specific.java @@ -15,9 +15,6 @@ */ package one.util.streamex; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; import java.util.function.DoublePredicate; import java.util.function.IntPredicate; import java.util.function.LongPredicate; diff --git a/src/main/java-mr/9/one/util/streamex/VerSpec.java b/src/main/java-mr/9/one/util/streamex/VerSpec.java index 1ab9671a..92c5be56 100644 --- a/src/main/java-mr/9/one/util/streamex/VerSpec.java +++ b/src/main/java-mr/9/one/util/streamex/VerSpec.java @@ -17,5 +17,5 @@ package one.util.streamex; /* package */ interface VerSpec { - VersionSpecific VER_SPEC = new Java9Specific(); + VersionSpecific VER_SPEC = new Java9Specific(); } diff --git a/src/main/java/one/util/streamex/AbstractStreamEx.java b/src/main/java/one/util/streamex/AbstractStreamEx.java index fffca528..5c7216e1 100644 --- a/src/main/java/one/util/streamex/AbstractStreamEx.java +++ b/src/main/java/one/util/streamex/AbstractStreamEx.java @@ -35,12 +35,12 @@ public abstract class AbstractStreamEx> exte BaseStreamEx, Spliterator, S> implements Stream, Iterable { @SuppressWarnings("unchecked") AbstractStreamEx(Stream stream, StreamContext context) { - super((Stream)stream, context); + super((Stream) stream, context); } @SuppressWarnings("unchecked") AbstractStreamEx(Spliterator spliterator, StreamContext context) { - super((Spliterator)spliterator, context); + super((Spliterator) spliterator, context); } @Override @@ -1178,8 +1178,7 @@ public S prepend(Stream other) { * operation. * * @param other other stream to replace the contents of this stream if this stream is empty. - * @return the stream which contents is replaced by other stream contents only if - * this stream is empty. + * @return the stream which contents is replaced by other stream contents only if this stream is empty. * @since 0.6.6 */ public S ifEmpty(Stream other) { @@ -1221,7 +1220,7 @@ public List toList() { @SuppressWarnings("unchecked") public List toImmutableList() { Object[] array = toArray(Object[]::new); - switch(array.length) { + switch (array.length) { case 0: return Collections.emptyList(); case 1: @@ -1821,6 +1820,6 @@ public S prefix(BinaryOperator op) { @SuppressWarnings("unchecked") @Override public U chain(Function mapper) { - return mapper.apply((S)this); + return mapper.apply((S) this); } } diff --git a/src/main/java/one/util/streamex/BaseStreamEx.java b/src/main/java/one/util/streamex/BaseStreamEx.java index 4309060c..f622b23b 100644 --- a/src/main/java/one/util/streamex/BaseStreamEx.java +++ b/src/main/java/one/util/streamex/BaseStreamEx.java @@ -167,5 +167,5 @@ public void close() { * @return the result of the function invocation. * @since 0.5.4 */ - abstract public U chain(Function mapper); + public abstract U chain(Function mapper); } diff --git a/src/main/java/one/util/streamex/CancellableCollector.java b/src/main/java/one/util/streamex/CancellableCollector.java index 33e05fc0..33448fb7 100644 --- a/src/main/java/one/util/streamex/CancellableCollector.java +++ b/src/main/java/one/util/streamex/CancellableCollector.java @@ -20,5 +20,5 @@ import java.util.stream.Collector; /* package */ abstract class CancellableCollector implements Collector { - abstract Predicate finished(); + abstract Predicate finished(); } diff --git a/src/main/java/one/util/streamex/CollapseSpliterator.java b/src/main/java/one/util/streamex/CollapseSpliterator.java index 2ec9dbcd..94665492 100644 --- a/src/main/java/one/util/streamex/CollapseSpliterator.java +++ b/src/main/java/one/util/streamex/CollapseSpliterator.java @@ -97,7 +97,7 @@ public boolean tryAdvance(Consumer action) { return true; } } - if (a == NONE) {// start + if (a == NONE) { // start if (!source.tryAdvance(this)) { return accept(pushRight(none(), none()), action); } diff --git a/src/main/java/one/util/streamex/CombinationSpliterator.java b/src/main/java/one/util/streamex/CombinationSpliterator.java index 275623d5..20e657a7 100644 --- a/src/main/java/one/util/streamex/CombinationSpliterator.java +++ b/src/main/java/one/util/streamex/CombinationSpliterator.java @@ -31,6 +31,7 @@ public CombinationSpliterator(int n, long pos, long fence, int[] value) { this.fence = fence; this.value = value; } + @Override public void forEachRemaining(Consumer action) { long rest = pos - fence; diff --git a/src/main/java/one/util/streamex/EntryStream.java b/src/main/java/one/util/streamex/EntryStream.java index efb8cb60..4fdfad5f 100644 --- a/src/main/java/one/util/streamex/EntryStream.java +++ b/src/main/java/one/util/streamex/EntryStream.java @@ -253,7 +253,7 @@ public EntryStream flatMapToValue( * @since 0.3.0 */ public StreamEx flatMapKeyValue(BiFunction> mapper) { - return this. flatMap(toFunction(mapper)); + return this.flatMap(toFunction(mapper)); } /** @@ -516,7 +516,7 @@ public EntryStream mapValues(Function value * @return the new stream */ public StreamEx mapKeyValue(BiFunction mapper) { - return this. map(toFunction(mapper)); + return this.map(toFunction(mapper)); } /** diff --git a/src/main/java/one/util/streamex/HeadTailSpliterator.java b/src/main/java/one/util/streamex/HeadTailSpliterator.java index 4de4c115..683766f6 100644 --- a/src/main/java/one/util/streamex/HeadTailSpliterator.java +++ b/src/main/java/one/util/streamex/HeadTailSpliterator.java @@ -45,10 +45,10 @@ @Override public boolean tryAdvance(Consumer action) { - if(!init()) + if (!init()) return false; target = TailSpliterator.tryAdvanceWithTail(target, action); - if(target == null) { + if (target == null) { context = null; return false; } @@ -57,7 +57,7 @@ public boolean tryAdvance(Consumer action) { @Override public Spliterator tryAdvanceOrTail(Consumer action) { - if(!init()) + if (!init()) return null; Spliterator tail = target; target = null; @@ -67,7 +67,7 @@ public Spliterator tryAdvanceOrTail(Consumer action) { @Override public void forEachRemaining(Consumer action) { - if(!init()) + if (!init()) return; TailSpliterator.forEachWithTail(target, action); target = null; @@ -80,20 +80,20 @@ public Spliterator forEachOrTail(Consumer action) { } private boolean init() { - if(context == null) + if (context == null) return false; - if(target == null) { + if (target == null) { Box first = new Box<>(); source = TailSpliterator.tryAdvanceWithTail(source, first); Stream stream = source == null ? emptyMapper.get() : mapper.apply(first.a, StreamEx.of(source)); source = null; mapper = null; emptyMapper = null; - if(stream == null) { + if (stream == null) { target = Spliterators.emptySpliterator(); } else { StreamContext ctx = StreamContext.of(stream); - if(ctx.closeHandler != null) + if (ctx.closeHandler != null) context.onClose(ctx.closeHandler); target = stream.spliterator(); } @@ -103,7 +103,7 @@ private boolean init() { @Override public long estimateSize() { - if(context == null) + if (context == null) return 0; return (target == null ? source : target).estimateSize(); } diff --git a/src/main/java/one/util/streamex/IfEmptySpliterator.java b/src/main/java/one/util/streamex/IfEmptySpliterator.java index b480e17b..239ad5d3 100644 --- a/src/main/java/one/util/streamex/IfEmptySpliterator.java +++ b/src/main/java/one/util/streamex/IfEmptySpliterator.java @@ -106,7 +106,7 @@ public long estimateSize() { @Override public int characteristics() { - if(alt == null) { + if (alt == null) { return spltr.characteristics() & (~SORTED); } return (spltr.characteristics() & alt.characteristics() & (~SORTED)) | diff --git a/src/main/java/one/util/streamex/Internals.java b/src/main/java/one/util/streamex/Internals.java index bdb45f07..2000fccd 100644 --- a/src/main/java/one/util/streamex/Internals.java +++ b/src/main/java/one/util/streamex/Internals.java @@ -332,7 +332,7 @@ public Set> entrySet() { return new AbstractSet>() { @Override public Iterator> iterator() { - return Arrays.> asList(new SimpleEntry<>(Boolean.TRUE, trueValue), + return Arrays.>asList(new SimpleEntry<>(Boolean.TRUE, trueValue), new SimpleEntry<>(Boolean.FALSE, falseValue)).iterator(); } @@ -488,8 +488,8 @@ static PartialCollector joining(CharSequence delimiter, C }; Supplier supplier = StringBuilder::new; if (hasPS) - return new PartialCollector<>(supplier, merger, sb -> String.valueOf(prefix) + sb + - suffix, NO_CHARACTERISTICS); + return new PartialCollector<>(supplier, merger, sb -> String.valueOf(prefix) + sb + suffix, + NO_CHARACTERISTICS); return new PartialCollector<>(supplier, merger, StringBuilder::toString, NO_CHARACTERISTICS); } } @@ -867,7 +867,7 @@ public Object[] toArray() { /** * A spliterator which may perform tail-stream optimization * - * @param + * @param the type of elements returned by this spliterator */ interface TailSpliterator extends Spliterator { /** diff --git a/src/main/java/one/util/streamex/Joining.java b/src/main/java/one/util/streamex/Joining.java index cf204c7a..25be4a62 100644 --- a/src/main/java/one/util/streamex/Joining.java +++ b/src/main/java/one/util/streamex/Joining.java @@ -396,13 +396,13 @@ public Joining maxGraphemes(int limit) { * ellipsis sequence. The cutting strategy is mostly irrelevant for this * mode except {@link #cutBeforeDelimiter()}. *

- * The collector returned by this method is short-circuiting: + * The collector returned by this method is + * short-circuiting: * it may not process all the input elements if the limit is reached. * - * @param limit the maximal number of input elements in the resulting - * String. + * @param limit the maximal number of input elements in the resulting String. * @return a new {@code Collector} which will produce String no longer than - * given limit. + * given limit. * @since 0.6.7 */ public Joining maxElements(int limit) { diff --git a/src/main/java/one/util/streamex/MoreCollectors.java b/src/main/java/one/util/streamex/MoreCollectors.java index 473ed34a..494e9949 100644 --- a/src/main/java/one/util/streamex/MoreCollectors.java +++ b/src/main/java/one/util/streamex/MoreCollectors.java @@ -188,7 +188,7 @@ private MoreCollectors() { * @since 0.3.8 */ public static Collector> distinctBy(Function mapper) { - return Collector., List> of(LinkedHashMap::new, (map, t) -> map.putIfAbsent(mapper.apply( + return Collector., List>of(LinkedHashMap::new, (map, t) -> map.putIfAbsent(mapper.apply( t), t), (m1, m2) -> { for (Entry e : m2.entrySet()) { m1.putIfAbsent(e.getKey(), e.getValue()); @@ -399,7 +399,7 @@ private MoreCollectors() { * @see #maxAll() */ public static , A, D> Collector maxAll(Collector downstream) { - return maxAll(Comparator. naturalOrder(), downstream); + return maxAll(Comparator.naturalOrder(), downstream); } /** @@ -414,7 +414,7 @@ private MoreCollectors() { * @see #maxAll(Collector) */ public static > Collector> maxAll() { - return maxAll(Comparator. naturalOrder(), Collectors.toList()); + return maxAll(Comparator.naturalOrder(), Collectors.toList()); } /** @@ -472,7 +472,7 @@ private MoreCollectors() { * @see #minAll() */ public static , A, D> Collector minAll(Collector downstream) { - return maxAll(Comparator. reverseOrder(), downstream); + return maxAll(Comparator.reverseOrder(), downstream); } /** @@ -487,7 +487,7 @@ private MoreCollectors() { * @see #minAll(Collector) */ public static > Collector> minAll() { - return maxAll(Comparator. reverseOrder(), Collectors.toList()); + return maxAll(Comparator.reverseOrder(), Collectors.toList()); } /** @@ -628,7 +628,7 @@ private MoreCollectors() { public static Collector> tail(int n) { if (n <= 0) return empty(); - return Collector., List> of(ArrayDeque::new, (acc, t) -> { + return Collector., List>of(ArrayDeque::new, (acc, t) -> { if (acc.size() == n) acc.pollFirst(); acc.addLast(t); @@ -700,7 +700,7 @@ private MoreCollectors() { * n stream elements or less if the stream was shorter. */ public static > Collector> greatest(int n) { - return least(Comparator. reverseOrder(), n); + return least(Comparator.reverseOrder(), n); } /** @@ -748,7 +748,7 @@ private MoreCollectors() { return list; return new ArrayList<>(list.subList(0, n)); }); - return Collector., List> of(() -> new Limiter<>(n, comparator), Limiter::put, Limiter::putAll, + return Collector., List>of(() -> new Limiter<>(n, comparator), Limiter::put, Limiter::putAll, pq -> { pq.sort(); return new ArrayList<>(pq); @@ -783,7 +783,7 @@ private MoreCollectors() { * stream elements or less if the stream was shorter. */ public static > Collector> least(int n) { - return least(Comparator. naturalOrder(), n); + return least(Comparator.naturalOrder(), n); } /** @@ -803,6 +803,7 @@ class Container { long count = 0; long index = -1; } + return Collector.of(Container::new, (c, t) -> { if (c.index == -1 || comparator.compare(c.value, t) > 0) { c.value = t; diff --git a/src/main/java/one/util/streamex/PairSpliterator.java b/src/main/java/one/util/streamex/PairSpliterator.java index 294f6da2..f7bb5ca1 100644 --- a/src/main/java/one/util/streamex/PairSpliterator.java +++ b/src/main/java/one/util/streamex/PairSpliterator.java @@ -121,13 +121,13 @@ void clear() { PairSpliterator(S source, int mode, T headTail) { this.source = source; this.mode = mode; - if(mode != MODE_PAIRS) { + if (mode != MODE_PAIRS) { Sink sink = new Sink<>(this.lock); Sink other = new Sink<>(this.lock); sink.other = other; other.other = sink; other.push(headTail, null, true); - if(mode == MODE_MAP_FIRST || mode == MODE_MAP_FIRST_OR_ELSE) + if (mode == MODE_MAP_FIRST || mode == MODE_MAP_FIRST_OR_ELSE) this.left = sink; else this.right = sink; @@ -188,16 +188,16 @@ static class PSOfRef extends PairSpliterator, R, PSOfRef // Must be called only if T == R @SuppressWarnings("unchecked") PSOfRef(Function mapper, Spliterator source, boolean first) { - super(source, first ? MODE_MAP_FIRST : MODE_MAP_LAST, (T)HEAD_TAIL); - BiFunction m = first ? - ((a, b) -> a == HEAD_TAIL ? mapper.apply(b) : (T)b) : - ((a, b) -> b == HEAD_TAIL ? mapper.apply(a) : (T)a); + super(source, first ? MODE_MAP_FIRST : MODE_MAP_LAST, (T) HEAD_TAIL); + BiFunction m = first ? + ((a, b) -> a == HEAD_TAIL ? mapper.apply(b) : (T) b) : + ((a, b) -> b == HEAD_TAIL ? mapper.apply(a) : (T) a); this.mapper = (BiFunction) m; } @SuppressWarnings("unchecked") PSOfRef(Function boundMapper, Function elseMapper, Spliterator source, boolean first) { - super(source, first ? MODE_MAP_FIRST_OR_ELSE : MODE_MAP_LAST_OR_ELSE, (T)HEAD_TAIL); + super(source, first ? MODE_MAP_FIRST_OR_ELSE : MODE_MAP_LAST_OR_ELSE, (T) HEAD_TAIL); this.mapper = first ? ((a, b) -> a == HEAD_TAIL ? boundMapper.apply(b) : elseMapper.apply(b)) : ((a, b) -> b == HEAD_TAIL ? boundMapper.apply(a) : elseMapper.apply(a)); @@ -264,14 +264,14 @@ public Spliterator tryAdvanceOrTail(Consumer action) { return this; } @SuppressWarnings("unchecked") - Spliterator s = (Spliterator)source; + Spliterator s = (Spliterator) source; source = null; return s; } @Override public Spliterator forEachOrTail(Consumer action) { - if(mode != MODE_MAP_FIRST || right != EMPTY) { + if (mode != MODE_MAP_FIRST || right != EMPTY) { forEachRemaining(action); return null; } @@ -301,7 +301,7 @@ public void accept(int t) { } private BiConsumer fn(IntConsumer action) { - switch(mode) { + switch (mode) { case MODE_MAP_FIRST: return (a, b) -> action.accept(a == null ? unaryMapper.applyAsInt(b) : b); case MODE_MAP_LAST: @@ -365,7 +365,7 @@ public void accept(long t) { } private BiConsumer fn(LongConsumer action) { - switch(mode) { + switch (mode) { case MODE_MAP_FIRST: return (a, b) -> action.accept(a == null ? unaryMapper.applyAsLong(b) : b); case MODE_MAP_LAST: @@ -429,7 +429,7 @@ public void accept(double t) { } private BiConsumer fn(DoubleConsumer action) { - switch(mode) { + switch (mode) { case MODE_MAP_FIRST: return (a, b) -> action.accept(a == null ? unaryMapper.applyAsDouble(b) : b); case MODE_MAP_LAST: diff --git a/src/main/java/one/util/streamex/PrefixOps.java b/src/main/java/one/util/streamex/PrefixOps.java index 451d5e0c..21889889 100644 --- a/src/main/java/one/util/streamex/PrefixOps.java +++ b/src/main/java/one/util/streamex/PrefixOps.java @@ -35,7 +35,7 @@ /** * @author Tagir Valeev */ -/* package */ abstract class PrefixOps> extends CloneableSpliterator>{ +/* package */ abstract class PrefixOps> extends CloneableSpliterator> { private static final int BUF_SIZE = 128; S source; @@ -51,15 +51,15 @@ @Override public Spliterator trySplit() { - if(acc != NONE) { + if (acc != NONE) { return null; } @SuppressWarnings("unchecked") S prefix = (S) source.trySplit(); - if(prefix == null) { + if (prefix == null) { return null; } - if(accRef == null) { + if (accRef == null) { accRef = new AtomicReference<>(none()); } PrefixOps pref = doClone(); @@ -91,7 +91,7 @@ static final class OfRef extends AbstractSpliterator implements Consumer action) { - if(!source.tryAdvance(this)) + if (!source.tryAdvance(this)) return false; action.accept(acc); return true; @@ -107,7 +107,7 @@ public void forEachRemaining(Consumer action) { @Override public void accept(T next) { - if(started) { + if (started) { acc = op.apply(acc, next); } else { started = true; @@ -130,7 +130,7 @@ static final class OfInt extends AbstractIntSpliterator implements IntConsumer { @Override public boolean tryAdvance(IntConsumer action) { - if(!source.tryAdvance(this)) + if (!source.tryAdvance(this)) return false; action.accept(acc); return true; @@ -146,7 +146,7 @@ public void forEachRemaining(IntConsumer action) { @Override public void accept(int next) { - if(started) { + if (started) { acc = op.applyAsInt(acc, next); } else { started = true; @@ -169,7 +169,7 @@ static final class OfLong extends AbstractLongSpliterator implements LongConsume @Override public boolean tryAdvance(LongConsumer action) { - if(!source.tryAdvance(this)) + if (!source.tryAdvance(this)) return false; action.accept(acc); return true; @@ -185,7 +185,7 @@ public void forEachRemaining(LongConsumer action) { @Override public void accept(long next) { - if(started) { + if (started) { acc = op.applyAsLong(acc, next); } else { started = true; @@ -208,7 +208,7 @@ static final class OfDouble extends AbstractDoubleSpliterator implements DoubleC @Override public boolean tryAdvance(DoubleConsumer action) { - if(!source.tryAdvance(this)) + if (!source.tryAdvance(this)) return false; action.accept(acc); return true; @@ -224,7 +224,7 @@ public void forEachRemaining(DoubleConsumer action) { @Override public void accept(double next) { - if(started) { + if (started) { acc = op.applyAsDouble(acc, next); } else { started = true; @@ -243,7 +243,7 @@ static final class OfUnordRef extends PrefixOps> implements @Override public boolean tryAdvance(Consumer action) { - if(!source.tryAdvance(this)) { + if (!source.tryAdvance(this)) { return false; } action.accept(acc); @@ -252,37 +252,37 @@ public boolean tryAdvance(Consumer action) { @Override public void forEachRemaining(Consumer action) { - if(accRef == null) { + if (accRef == null) { source.forEachRemaining(next -> action.accept(acc = op.apply(acc, next))); } else { @SuppressWarnings("unchecked") T[] buf = (T[]) new Object[BUF_SIZE]; source.forEachRemaining(next -> { - if(idx == 0) { + if (idx == 0) { buf[idx++] = next; } else { - T prev = buf[idx-1]; + T prev = buf[idx - 1]; buf[idx++] = localOp.apply(prev, next); - if(idx == buf.length) { + if (idx == buf.length) { drain(action, buf); idx = 0; } } }); - if(idx > 0) + if (idx > 0) drain(action, buf); } } private void drain(Consumer action, T[] buf) { - T last = buf[idx-1]; + T last = buf[idx - 1]; T acc = accRef.getAndAccumulate(last, op); - if(acc != NONE) { - for(int i=0; i action, T[] buf) { @Override public void accept(T next) { - if(accRef == null) { + if (accRef == null) { acc = op.apply(acc, next); } else { acc = accRef.accumulateAndGet(next, op); diff --git a/src/main/java/one/util/streamex/PrependSpliterator.java b/src/main/java/one/util/streamex/PrependSpliterator.java index 7f9042c0..55e642c2 100644 --- a/src/main/java/one/util/streamex/PrependSpliterator.java +++ b/src/main/java/one/util/streamex/PrependSpliterator.java @@ -33,7 +33,7 @@ public PrependSpliterator(Spliterator source, T element) { this.source = source; this.element = element; - this.mode = source.estimateSize() < Long.MAX_VALUE-1 ? 1 : 2; + this.mode = source.estimateSize() < Long.MAX_VALUE - 1 ? 1 : 2; } @Override @@ -96,7 +96,7 @@ public long estimateSize() { @Override public int characteristics() { - switch(mode) { + switch (mode) { case 1: return source.characteristics() & (ORDERED | SIZED | SUBSIZED); case 2: @@ -105,4 +105,4 @@ public int characteristics() { return source.characteristics(); } } -} \ No newline at end of file +} diff --git a/src/main/java/one/util/streamex/StreamContext.java b/src/main/java/one/util/streamex/StreamContext.java index a92d92ec..e33dcbe0 100644 --- a/src/main/java/one/util/streamex/StreamContext.java +++ b/src/main/java/one/util/streamex/StreamContext.java @@ -98,7 +98,7 @@ void close() { } static Runnable compose(Runnable r1, Runnable r2) { - if(r1 == null) + if (r1 == null) return r2; return () -> { try { diff --git a/src/main/java/one/util/streamex/StreamEx.java b/src/main/java/one/util/streamex/StreamEx.java index ea840b87..a0e77a4c 100644 --- a/src/main/java/one/util/streamex/StreamEx.java +++ b/src/main/java/one/util/streamex/StreamEx.java @@ -806,7 +806,7 @@ public String joining(CharSequence delimiter, CharSequence prefix, CharSequence */ @SuppressWarnings("unchecked") public A[] toArray(Class elementClass) { - return stream().toArray(size -> (A[])Array.newInstance(elementClass, size)); + return stream().toArray(size -> (A[]) Array.newInstance(elementClass, size)); } /** @@ -836,7 +836,7 @@ public A[] toArray(Class elementClass) { */ @SuppressWarnings("unchecked") public A[] toArray(A[] emptyArray) { - if(emptyArray.length != 0) { + if (emptyArray.length != 0) { throw new IllegalArgumentException("Empty array must be supplied"); } return stream().toArray(size -> size == 0 ? emptyArray @@ -1912,7 +1912,7 @@ public StreamEx zipWith(BaseStream other, BiFunction EntryStream zipWith(Stream other) { - return zipWith((BaseStream)other); + return zipWith((BaseStream) other); } /** diff --git a/src/main/java/one/util/streamex/TailConcatSpliterator.java b/src/main/java/one/util/streamex/TailConcatSpliterator.java index 8cdb2f7a..2b621cd7 100644 --- a/src/main/java/one/util/streamex/TailConcatSpliterator.java +++ b/src/main/java/one/util/streamex/TailConcatSpliterator.java @@ -52,7 +52,7 @@ public boolean tryAdvance(Consumer action) { } left = null; } - if(right != null) + if (right != null) right = TailSpliterator.tryAdvanceWithTail(right, action); return right != null; } @@ -73,7 +73,7 @@ public Spliterator tryAdvanceOrTail(Consumer action) { public void forEachRemaining(Consumer action) { if (left != null) left.forEachRemaining(action); - if(right != null) + if (right != null) TailSpliterator.forEachWithTail(right, action); } @@ -106,4 +106,4 @@ public long estimateSize() { public int characteristics() { return characteristics; } -} \ No newline at end of file +} diff --git a/src/main/java/one/util/streamex/TakeDrop.java b/src/main/java/one/util/streamex/TakeDrop.java index b2424d01..b5db599e 100644 --- a/src/main/java/one/util/streamex/TakeDrop.java +++ b/src/main/java/one/util/streamex/TakeDrop.java @@ -154,10 +154,10 @@ public boolean tryAdvance(Consumer action) { @Override public Spliterator trySplit() { Spliterator prefix = source.trySplit(); - if(prefix == null) { + if (prefix == null) { return null; } - if(checked.get()) { + if (checked.get()) { return drop ? prefix : Spliterators.emptySpliterator(); } UnorderedTDOfRef clone = doClone(); diff --git a/src/main/java/one/util/streamex/TreeSpliterator.java b/src/main/java/one/util/streamex/TreeSpliterator.java index 118fb4cb..cf456e92 100644 --- a/src/main/java/one/util/streamex/TreeSpliterator.java +++ b/src/main/java/one/util/streamex/TreeSpliterator.java @@ -18,7 +18,8 @@ import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collections; -import java.util.List;import java.util.Map.Entry; +import java.util.List; +import java.util.Map.Entry; import java.util.Spliterator; import java.util.function.BiFunction; import java.util.function.Consumer; @@ -45,17 +46,17 @@ boolean advance() { List, Stream>> spltrs = spliterators; - if(spltrs == null) { + if (spltrs == null) { spliterators = new ArrayList<>(); return true; } - for(int lastIdx = spltrs.size()-1; lastIdx >= 0; lastIdx--) { + for (int lastIdx = spltrs.size() - 1; lastIdx >= 0; lastIdx--) { PairBox, Stream> pair = spltrs.get(lastIdx); Spliterator spltr = pair.a; - if(spltr.tryAdvance(this)) { + if (spltr.tryAdvance(this)) { return true; } - if(pair.b != null) + if (pair.b != null) pair.b.close(); spltrs.remove(lastIdx); } @@ -63,7 +64,7 @@ boolean advance() { } boolean append(Stream stream) { - if(stream != null) { + if (stream != null) { spliterators.add(new PairBox<>(stream.spliterator(), stream)); } return true; @@ -75,21 +76,21 @@ boolean append(Stream stream) { @Override public Spliterator trySplit() { - if(spliterators == null) { + if (spliterators == null) { spliterators = new ArrayList<>(); Stream stream = getStart(); - if(stream != null) { + if (stream != null) { spliterators.add(new PairBox<>(stream.parallel().spliterator(), null)); closeHandler = stream::close; } return new ConstSpliterator.OfRef<>(getStartElement(), 1, true); } int size = spliterators.size(); - if(size != 1) { + if (size != 1) { return null; } Spliterator prefix = spliterators.get(0).a.trySplit(); - if(prefix == null) + if (prefix == null) return null; TreeSpliterator clone = doClone(); clone.size /= 2; @@ -122,34 +123,34 @@ public void run() { @Override public void close() { - if(spliterators != null) { + if (spliterators != null) { Throwable t = null; - for(int i=spliterators.size()-1; i>=0; i--) { + for (int i = spliterators.size() - 1; i >= 0; i--) { try { Stream stream = spliterators.get(i).b; - if(stream != null) + if (stream != null) stream.close(); } catch (Error | RuntimeException e) { - if(t == null) + if (t == null) t = e; else t.addSuppressed(e); } } - if(closeHandler != null) { + if (closeHandler != null) { try { closeHandler.run(); } catch (Error | RuntimeException e) { - if(t == null) + if (t == null) t = e; else t.addSuppressed(e); } } - if(t instanceof RuntimeException) - throw (RuntimeException)t; - if(t instanceof Error) - throw (Error)t; + if (t instanceof RuntimeException) + throw (RuntimeException) t; + if (t instanceof Error) + throw (Error ) t; } } @@ -194,7 +195,7 @@ static class Plain extends TreeSpliterator { @Override public boolean tryAdvance(Consumer action) { - if(!advance()) + if (!advance()) return false; T e = this.cur; action.accept(e); @@ -204,11 +205,11 @@ public boolean tryAdvance(Consumer action) { @Override public void forEachRemaining(Consumer action) { Acceptor acceptor = new Acceptor<>(action, mapper); - if(spliterators != null) { - for(int i=spliterators.size()-1; i>=0; i--) { + if (spliterators != null) { + for (int i = spliterators.size() - 1; i >= 0; i--) { PairBox, Stream> pair = spliterators.get(i); pair.a.forEachRemaining(acceptor); - if(pair.b != null) + if (pair.b != null) pair.b.close(); } } else { @@ -249,8 +250,8 @@ public void accept(T t) { return; } action.accept(new AbstractMap.SimpleImmutableEntry<>(depth, t)); - try(Stream stream = mapper.apply(depth, t)) { - if(stream != null) { + try (Stream stream = mapper.apply(depth, t)) { + if (stream != null) { depth++; stream.spliterator().forEachRemaining(this); depth--; @@ -271,7 +272,7 @@ static class Depth extends TreeSpliterator> { @Override public boolean tryAdvance(Consumer> action) { - if(!advance()) + if (!advance()) return false; T e = this.cur; int depth = initialDepth + spliterators.size(); @@ -282,12 +283,12 @@ public boolean tryAdvance(Consumer> action) { @Override public void forEachRemaining(Consumer> action) { DepthAcceptor acceptor = new DepthAcceptor<>(action, mapper, initialDepth); - if(spliterators != null) { - for(int i=spliterators.size()-1; i>=0; i--) { + if (spliterators != null) { + for (int i = spliterators.size() - 1; i >= 0; i--) { PairBox, Stream> pair = spliterators.get(i); acceptor.depth = i + 1; pair.a.forEachRemaining(acceptor); - if(pair.b != null) + if (pair.b != null) pair.b.close(); } } else { diff --git a/src/main/java/one/util/streamex/VerSpec.java b/src/main/java/one/util/streamex/VerSpec.java index 72461457..5e4b3c85 100644 --- a/src/main/java/one/util/streamex/VerSpec.java +++ b/src/main/java/one/util/streamex/VerSpec.java @@ -17,5 +17,5 @@ package one.util.streamex; /* package */ interface VerSpec { - VersionSpecific VER_SPEC = new VersionSpecific(); + VersionSpecific VER_SPEC = new VersionSpecific(); } diff --git a/src/main/java/one/util/streamex/WithFirstSpliterator.java b/src/main/java/one/util/streamex/WithFirstSpliterator.java index 62ca3788..295ce92e 100644 --- a/src/main/java/one/util/streamex/WithFirstSpliterator.java +++ b/src/main/java/one/util/streamex/WithFirstSpliterator.java @@ -45,13 +45,13 @@ } private void acquire() { - if(lock != null && state == STATE_NONE) { + if (lock != null && state == STATE_NONE) { lock.lock(); } } private void release() { - if(lock != null && lock.isHeldByCurrentThread()) { + if (lock != null && lock.isHeldByCurrentThread()) { lock.unlock(); } } @@ -62,8 +62,7 @@ public boolean tryAdvance(Consumer action) { acquire(); try { doInit(); - } - finally { + } finally { release(); } } @@ -101,9 +100,9 @@ public void forEachRemaining(Consumer action) { acquire(); int myState = state; this.action = action; - if(myState == STATE_FIRST_READ || myState == STATE_INIT) { + if (myState == STATE_FIRST_READ || myState == STATE_INIT) { release(); - if(myState == STATE_FIRST_READ) { + if (myState == STATE_FIRST_READ) { state = STATE_INIT; accept(first); } @@ -124,22 +123,21 @@ public void forEachRemaining(Consumer action) { }; source.forEachRemaining(init.andThen(this)); this.action = null; - } - finally { + } finally { release(); } } @Override public Spliterator trySplit() { - if(state != STATE_NONE) + if (state != STATE_NONE) return null; Spliterator prefix; - if(lock == null) + if (lock == null) lock = new ReentrantLock(); acquire(); try { - if(state != STATE_NONE) + if (state != STATE_NONE) return null; prefix = source.trySplit(); if (prefix == null) diff --git a/src/main/java/one/util/streamex/ZipSpliterator.java b/src/main/java/one/util/streamex/ZipSpliterator.java index 6db1ecd2..f55ea88a 100644 --- a/src/main/java/one/util/streamex/ZipSpliterator.java +++ b/src/main/java/one/util/streamex/ZipSpliterator.java @@ -53,21 +53,21 @@ public boolean tryAdvance(Consumer action) { @Override public void forEachRemaining(Consumer action) { - if(!hasCharacteristics(SIZED)) { + if (!hasCharacteristics(SIZED)) { Spliterator.super.forEachRemaining(action); return; } long leftSize = left.getExactSizeIfKnown(); long rightSize = right.getExactSizeIfKnown(); - if(leftSize <= rightSize) { + if (leftSize <= rightSize) { left.forEachRemaining(u -> { - if(right.tryAdvance(r)) { + if (right.tryAdvance(r)) { action.accept(mapper.apply(u, r.a)); } }); } else { right.forEachRemaining(v -> { - if(left.tryAdvance(l)) { + if (left.tryAdvance(l)) { action.accept(mapper.apply(l.a, v)); } }); @@ -76,37 +76,30 @@ public void forEachRemaining(Consumer action) { @Override public Spliterator trySplit() { - if(trySplit && hasCharacteristics(SIZED | SUBSIZED)) - { + if (trySplit && hasCharacteristics(SIZED | SUBSIZED)) { Spliterator leftPrefix = left.trySplit(); - if(leftPrefix == null) + if (leftPrefix == null) return arraySplit(); Spliterator rightPrefix = right.trySplit(); - if(rightPrefix == null) - { + if (rightPrefix == null) { left = new TailConcatSpliterator<>(leftPrefix, left); return arraySplit(); } long leftSize = leftPrefix.getExactSizeIfKnown(); long rightSize = rightPrefix.getExactSizeIfKnown(); - if(leftSize >= 0 && rightSize >= 0) - { - if(leftSize == rightSize) - { + if (leftSize >= 0 && rightSize >= 0) { + if (leftSize == rightSize) { return new ZipSpliterator<>(leftPrefix, rightPrefix, mapper, true); } - if(Math.abs(leftSize-rightSize) < Math.min(BATCH_UNIT, Math.max(leftSize, rightSize)/8)) - { - if(leftSize < rightSize) - { + if (Math.abs(leftSize - rightSize) < Math.min(BATCH_UNIT, Math.max(leftSize, rightSize) / 8)) { + if (leftSize < rightSize) { @SuppressWarnings("unchecked") - U[] array = (U[]) new Object[(int) (rightSize-leftSize)]; + U[] array = (U[]) new Object[(int) (rightSize - leftSize)]; drainTo(array, left); leftPrefix = new TailConcatSpliterator<>(leftPrefix, Spliterators.spliterator(array, characteristics())); - } else - { + } else { @SuppressWarnings("unchecked") - V[] array = (V[]) new Object[(int) (leftSize-rightSize)]; + V[] array = (V[]) new Object[(int) (leftSize - rightSize)]; drainTo(array, right); rightPrefix = new TailConcatSpliterator<>(rightPrefix, Spliterators.spliterator(array, characteristics())); } @@ -131,14 +124,14 @@ private Spliterator arraySplit() { @SuppressWarnings("unchecked") R[] array = (R[]) new Object[n]; int index = drainTo(array, this); - if((batch = index) == 0) + if ((batch = index) == 0) return null; long s2 = estimateSize(); USOfRef prefix = new UnknownSizeSpliterator.USOfRef<>(array, 0, index); - if(hasCharacteristics(SUBSIZED)) + if (hasCharacteristics(SUBSIZED)) prefix.est = index; - else if(s == s2) - prefix.est = Math.max(index, s/2); + else if (s == s2) + prefix.est = Math.max(index, s / 2); else prefix.est = Math.max(index, s2 - s); return prefix; diff --git a/src/test/java/one/util/streamex/BaseStreamExTest.java b/src/test/java/one/util/streamex/BaseStreamExTest.java index c8cfc153..8cde0d3f 100644 --- a/src/test/java/one/util/streamex/BaseStreamExTest.java +++ b/src/test/java/one/util/streamex/BaseStreamExTest.java @@ -36,7 +36,7 @@ public class BaseStreamExTest { @Test public void testSpliterator() { - Spliterator spltr = Arrays.spliterator(new Integer[] {1,2,3}); + Spliterator spltr = Arrays.spliterator(new Integer[]{1, 2, 3}); StreamEx s = StreamEx.of(spltr); assertFalse(s.isParallel()); assertSame(spltr, s.spliterator()); @@ -59,9 +59,8 @@ public void testStreamConsumed() { @Test public void testClose() { List closeHandlers = new ArrayList<>(); - StreamEx stream = StreamEx.of(Stream.of(1,2,3).onClose(() -> closeHandlers.add("Orig stream"))) - .onClose(() -> closeHandlers.add("StreamEx")) - .map(x -> x*2) + StreamEx stream = StreamEx.of(Stream.of(1, 2, 3).onClose(() -> closeHandlers.add("Orig stream"))) + .onClose(() -> closeHandlers.add("StreamEx")).map(x -> x * 2) .onClose(() -> closeHandlers.add("After map")) .pairMap(Integer::sum) .onClose(() -> closeHandlers.add("After pairMap")) @@ -82,10 +81,12 @@ public void testClose() { @Test public void testCloseException() { AtomicBoolean flag = new AtomicBoolean(); - Function ex = str -> () -> {throw new IllegalStateException(str);}; - StreamEx stream = StreamEx.of(Stream.of(1,2,3).onClose(ex.apply("Orig stream"))) + Function ex = str -> () -> { + throw new IllegalStateException(str); + }; + StreamEx stream = StreamEx.of(Stream.of(1, 2, 3).onClose(ex.apply("Orig stream"))) .onClose(ex.apply("StreamEx")) - .map(x -> x*2) + .map(x -> x * 2) .onClose(() -> flag.set(true)) .pairMap(Integer::sum) .onClose(ex.apply("After pairMap")) @@ -96,8 +97,7 @@ public void testCloseException() { assertEquals(Arrays.asList(6, 5, 6, 10, 4), stream.toList()); try { stream.close(); - } - catch(IllegalStateException e) { + } catch (IllegalStateException e) { assertEquals("Orig stream", e.getMessage()); assertEquals(Arrays.asList("StreamEx", "After pairMap", "After append", "Prepended Stream", "Prepended StreamEx"), StreamEx.of(e.getSuppressed()).map(IllegalStateException.class::cast).map( diff --git a/src/test/java/one/util/streamex/CharSpliteratorTest.java b/src/test/java/one/util/streamex/CharSpliteratorTest.java index c7de6e53..fe4ec9d3 100644 --- a/src/test/java/one/util/streamex/CharSpliteratorTest.java +++ b/src/test/java/one/util/streamex/CharSpliteratorTest.java @@ -53,7 +53,7 @@ public void testSpliterator() { String[] inputs = { ",", "abcd,e,f,gh,,,i,j,kl,,,,,,", ",", "abcdasdfgsdfgsdfgsdfgsdfgsdgdfsgs", "abcdasdfgsdfgsdfgsdfgsdfgsdgdfsgs,", "abcdasdfgs,dfgsdfgsdfgsdfgsdgdfsgs", "abcd,e,f,gh,,,i,j,kl,,,,,,x", "abcd,e,f,gh,,,i,j,kl,,,,,,x,", - IntStreamEx.of(r, 0, 3).limit(r.nextInt(1000)+1).elements(new int[] { ',', 'a', 'b' }).charsToString() }; + IntStreamEx.of(r, 0, 3).limit(r.nextInt(1000) + 1).elements(new int[] { ',', 'a', 'b' }).charsToString() }; for (String input : inputs) { checkSpliterator(input, Arrays.asList(input.split(",")), () -> new CharSpliterator(input, ',', true)); checkSpliterator(input, Arrays.asList(input.split(",", -1)), () -> new CharSpliterator(input, ',', false)); diff --git a/src/test/java/one/util/streamex/CollapseSpliteratorTest.java b/src/test/java/one/util/streamex/CollapseSpliteratorTest.java index 3f2a13aa..d20c5c95 100644 --- a/src/test/java/one/util/streamex/CollapseSpliteratorTest.java +++ b/src/test/java/one/util/streamex/CollapseSpliteratorTest.java @@ -124,7 +124,7 @@ private static void multiSplit(Supplier> inputSpliterator) spliterators.add(split); } Collections.shuffle(spliterators, r); - repeat(spliterators.size(), i -> spliterators.get(i-1).forEachRemaining(result::add)); + repeat(spliterators.size(), i -> spliterators.get(i - 1).forEachRemaining(result::add)); assertEquals(6, result.size()); })); } diff --git a/src/test/java/one/util/streamex/DoubleStreamExTest.java b/src/test/java/one/util/streamex/DoubleStreamExTest.java index 08e70786..4ae8b316 100644 --- a/src/test/java/one/util/streamex/DoubleStreamExTest.java +++ b/src/test/java/one/util/streamex/DoubleStreamExTest.java @@ -465,7 +465,7 @@ public void testScanLeft() { // leaving scanner in known state private static DoubleStreamEx scannerDoubles(Scanner sc) { return DoubleStreamEx.produce(action -> { - if(sc.hasNextDouble()) + if (sc.hasNextDouble()) action.accept(sc.nextDouble()); return sc.hasNextDouble(); }); diff --git a/src/test/java/one/util/streamex/EmitterTest.java b/src/test/java/one/util/streamex/EmitterTest.java index b9a86ee8..3d82a0e8 100644 --- a/src/test/java/one/util/streamex/EmitterTest.java +++ b/src/test/java/one/util/streamex/EmitterTest.java @@ -127,7 +127,7 @@ public static DoubleEmitter flatTestDouble(int start) { } public static LongStreamEx primes() { - return ((LongEmitter)(action -> { + return ((LongEmitter) (action -> { action.accept(2); return primes(3, x -> x % 2 != 0); })).stream(); @@ -137,7 +137,7 @@ private static LongEmitter primes(long start, LongPredicate isPrime) { return action -> { long nextPrime = LongStreamEx.range(start, Long.MAX_VALUE, 2).findFirst(isPrime).getAsLong(); action.accept(nextPrime); - return primes(nextPrime+2, isPrime.and(x -> x % nextPrime != 0)); + return primes(nextPrime + 2, isPrime.and(x -> x % nextPrime != 0)); }; } diff --git a/src/test/java/one/util/streamex/EntryStreamTest.java b/src/test/java/one/util/streamex/EntryStreamTest.java index 5ac08232..ef454bca 100644 --- a/src/test/java/one/util/streamex/EntryStreamTest.java +++ b/src/test/java/one/util/streamex/EntryStreamTest.java @@ -384,7 +384,7 @@ public void testFlatMapKeys() { expected.put(3, asList("aaa", "bb")); expected.put(4, asList("bb")); assertEquals(expected, result); - assertEquals(0, EntryStream., String> of(null, "a").flatMapKeys(Function.identity()).count()); + assertEquals(0, EntryStream., String>of(null, "a").flatMapKeys(Function.identity()).count()); } @Test @@ -666,17 +666,18 @@ public void testOfTree() { .selectValues(String.class).grouping(TreeMap::new).toString())); Set set = new HashSet<>(); - try(EntryStream stream = EntryStream.ofTree("", (Integer depth, String str) -> depth >= 3 ? null : Stream.of("a", "b") + try (EntryStream stream = EntryStream.ofTree("", (Integer depth, String str) -> depth >= 3 ? null : Stream.of("a", "b") .map(str::concat).onClose(() -> set.add(depth)))) { assertEquals(15, stream.count()); } assertEquals(StreamEx.of(0, 1, 2).toSet(), set); boolean catched = false; - try(EntryStream stream = EntryStream.ofTree("", (Integer depth, String str) -> depth > 1000 ? null : Stream.of("a", "b") - .map(str::concat).onClose(() -> {throw new IllegalArgumentException(String.valueOf(depth));}))) { + try (EntryStream stream = EntryStream.ofTree("", (Integer depth, String str) -> depth > 1000 ? null : Stream.of("a", "b") + .map(str::concat).onClose(() -> { + throw new IllegalArgumentException(String.valueOf(depth)); + }))) { stream.count(); - } - catch(IllegalArgumentException iae) { + } catch (IllegalArgumentException iae) { catched = true; assertEquals("1000", iae.getMessage()); assertArrayEquals(IntStreamEx.rangeClosed(1000, 0, -1).toArray(), @@ -749,7 +750,7 @@ public void testImmutableMap() { @Test public void testInto() { - for(AbstractMap m : Arrays.>asList(new HashMap<>(), new TreeMap<>(), new ConcurrentHashMap<>())) { + for (AbstractMap m : Arrays.>asList(new HashMap<>(), new TreeMap<>(), new ConcurrentHashMap<>())) { AbstractMap res = EntryStream.of("a", 1, "b", 2, "c", 3).into(m); assertSame(m, res); assertEquals(EntryStream.of("a", 1, "b", 2, "c", 3).toMap(), m); diff --git a/src/test/java/one/util/streamex/IntStreamExTest.java b/src/test/java/one/util/streamex/IntStreamExTest.java index 6e873aec..a2d231cf 100644 --- a/src/test/java/one/util/streamex/IntStreamExTest.java +++ b/src/test/java/one/util/streamex/IntStreamExTest.java @@ -668,7 +668,7 @@ public void testScanLeft() { // leaving scanner in known state public static IntStreamEx scannerInts(Scanner sc) { return IntStreamEx.produce(action -> { - if(sc.hasNextInt()) + if (sc.hasNextInt()) action.accept(sc.nextInt()); return sc.hasNextInt(); }); @@ -684,10 +684,10 @@ public void testProduce() { @Test public void testOfInputStream() { byte[] data = new byte[] { 5, 3, 10, 1, 4, -1 }; - try(IntStream s = IntStreamEx.of(new ByteArrayInputStream(data))) { - assertEquals(22, s.map(b -> (byte)b).sum()); + try (IntStream s = IntStreamEx.of(new ByteArrayInputStream(data))) { + assertEquals(22, s.map(b -> (byte) b).sum()); } - try(IntStream s = IntStreamEx.of(new ByteArrayInputStream(data))) { + try (IntStream s = IntStreamEx.of(new ByteArrayInputStream(data))) { assertEquals(278, s.sum()); } InputStream is = new InputStream() { @@ -714,8 +714,8 @@ public void testAsInputStream() throws IOException { assertEquals(2, is.skip(2)); assertEquals(254, is.read(data)); assertEquals(-1, is.read()); - for(int i=0; i<254; i++) { - assertEquals((byte)(i+2), data[i]); + for (int i = 0; i < 254; i++) { + assertEquals((byte) (i + 2), data[i]); } assertEquals(0, data[254]); assertEquals(0, data[255]); diff --git a/src/test/java/one/util/streamex/LimiterTest.java b/src/test/java/one/util/streamex/LimiterTest.java index e8796bed..5184f24b 100644 --- a/src/test/java/one/util/streamex/LimiterTest.java +++ b/src/test/java/one/util/streamex/LimiterTest.java @@ -55,9 +55,9 @@ public void testLimiter() { List list = IntStreamEx.range(100000).boxed().toList(); exerciseLimiter("big", list, list, 50000, Comparator.naturalOrder()); exerciseLimiter("big", list, list, 49999, Comparator.naturalOrder()); - exerciseLimiter("big", list, list, 10000, Comparator.naturalOrder()); - exerciseLimiter("big", list, list, Integer.MAX_VALUE/3, Comparator.naturalOrder()); - exerciseLimiter("big", list, list, Integer.MAX_VALUE/2, Comparator.naturalOrder()); + exerciseLimiter("big", list, list, 10000, Comparator.naturalOrder()); + exerciseLimiter("big", list, list, Integer.MAX_VALUE / 3, Comparator.naturalOrder()); + exerciseLimiter("big", list, list, Integer.MAX_VALUE / 2, Comparator.naturalOrder()); } public static void exerciseLimiter(String msg, Collection input, Comparator comp) { diff --git a/src/test/java/one/util/streamex/LongStreamExTest.java b/src/test/java/one/util/streamex/LongStreamExTest.java index 0b5f90c1..a59a933b 100644 --- a/src/test/java/one/util/streamex/LongStreamExTest.java +++ b/src/test/java/one/util/streamex/LongStreamExTest.java @@ -553,7 +553,7 @@ public void testScanLeft() { // leaving scanner in known state public static LongStreamEx scannerLongs(Scanner sc) { return LongStreamEx.produce(action -> { - if(sc.hasNextLong()) + if (sc.hasNextLong()) action.accept(sc.nextLong()); return sc.hasNextLong(); }); diff --git a/src/test/java/one/util/streamex/MoreCollectorsTest.java b/src/test/java/one/util/streamex/MoreCollectorsTest.java index 85bcefca..67c5b07f 100644 --- a/src/test/java/one/util/streamex/MoreCollectorsTest.java +++ b/src/test/java/one/util/streamex/MoreCollectorsTest.java @@ -55,7 +55,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - return obj instanceof MyNumber && ((MyNumber)obj).value == value; + return obj instanceof MyNumber && ((MyNumber) obj).value == value; } @Override @@ -291,8 +291,8 @@ public void testMinIndex() { Supplier> supplier = () -> ints.stream().map(Object::toString); checkCollector("minIndex", OptionalLong.of(expectedMinString), supplier, MoreCollectors.minIndex()); checkCollector("maxIndex", OptionalLong.of(expectedMaxString), supplier, MoreCollectors.maxIndex()); - checkCollectorEmpty("minIndex", OptionalLong.empty(), MoreCollectors. minIndex()); - checkCollectorEmpty("maxIndex", OptionalLong.empty(), MoreCollectors. maxIndex()); + checkCollectorEmpty("minIndex", OptionalLong.empty(), MoreCollectors.minIndex()); + checkCollectorEmpty("maxIndex", OptionalLong.empty(), MoreCollectors.maxIndex()); }); } diff --git a/src/test/java/one/util/streamex/PairSpliteratorTest.java b/src/test/java/one/util/streamex/PairSpliteratorTest.java index 78a843b2..3edb25ef 100644 --- a/src/test/java/one/util/streamex/PairSpliteratorTest.java +++ b/src/test/java/one/util/streamex/PairSpliteratorTest.java @@ -49,21 +49,21 @@ public void testSpliterator() { checkSpliterator("ref", IntStreamEx.of(ints, 1, ints.length).boxed().prepend(ints[0] + 2).toList(), () -> new PairSpliterator.PSOfRef<>(a -> a + 2, Arrays.spliterator(ints), true)); checkSpliterator("int", IntStreamEx.of(ints, 1, ints.length).boxed().prepend(ints[0] + 2).toList(), - () -> new PairSpliterator.PSOfInt((a, b) -> b, a -> a+2, Arrays.spliterator(ints), PairSpliterator.MODE_MAP_FIRST)); + () -> new PairSpliterator.PSOfInt((a, b) -> b, a -> a + 2, Arrays.spliterator(ints), PairSpliterator.MODE_MAP_FIRST)); checkSpliterator("long", LongStreamEx.of(longs, 1, longs.length).boxed().prepend(longs[0] + 2).toList(), - () -> new PairSpliterator.PSOfLong((a, b) -> b, a -> a+2, Arrays.spliterator(longs), PairSpliterator.MODE_MAP_FIRST)); - checkSpliterator("double", DoubleStreamEx.of(doubles, 1, doubles.length).boxed().prepend(doubles[0] + 2).toList(), - () -> new PairSpliterator.PSOfDouble((a, b) -> b, a -> a+2, Arrays.spliterator(doubles), PairSpliterator.MODE_MAP_FIRST)); + () -> new PairSpliterator.PSOfLong((a, b) -> b, a -> a + 2, Arrays.spliterator(longs), PairSpliterator.MODE_MAP_FIRST)); + checkSpliterator("double", DoubleStreamEx.of(doubles, 1, doubles.length).boxed().prepend(doubles[0] + 2).toList(), + () -> new PairSpliterator.PSOfDouble((a, b) -> b, a -> a + 2, Arrays.spliterator(doubles), PairSpliterator.MODE_MAP_FIRST)); // mapLast - checkSpliterator("ref", IntStreamEx.of(ints, 0, ints.length-1).boxed().append(ints[ints.length-1] + 2).toList(), + checkSpliterator("ref", IntStreamEx.of(ints, 0, ints.length - 1).boxed().append(ints[ints.length - 1] + 2).toList(), () -> new PairSpliterator.PSOfRef<>(a -> a + 2, Arrays.spliterator(ints), false)); - checkSpliterator("int", IntStreamEx.of(ints, 0, ints.length-1).boxed().append(ints[ints.length-1] + 2).toList(), - () -> new PairSpliterator.PSOfInt((a, b) -> a, a -> a+2, Arrays.spliterator(ints), PairSpliterator.MODE_MAP_LAST)); - checkSpliterator("long", LongStreamEx.of(longs, 0, longs.length-1).boxed().append(longs[longs.length-1] + 2).toList(), - () -> new PairSpliterator.PSOfLong((a, b) -> a, a -> a+2, Arrays.spliterator(longs), PairSpliterator.MODE_MAP_LAST)); - checkSpliterator("double", DoubleStreamEx.of(doubles, 0, doubles.length-1).boxed().append(doubles[doubles.length-1] + 2).toList(), - () -> new PairSpliterator.PSOfDouble((a, b) -> a, a -> a+2, Arrays.spliterator(doubles), PairSpliterator.MODE_MAP_LAST)); + checkSpliterator("int", IntStreamEx.of(ints, 0, ints.length - 1).boxed().append(ints[ints.length - 1] + 2).toList(), + () -> new PairSpliterator.PSOfInt((a, b) -> a, a -> a + 2, Arrays.spliterator(ints), PairSpliterator.MODE_MAP_LAST)); + checkSpliterator("long", LongStreamEx.of(longs, 0, longs.length - 1).boxed().append(longs[longs.length - 1] + 2).toList(), + () -> new PairSpliterator.PSOfLong((a, b) -> a, a -> a + 2, Arrays.spliterator(longs), PairSpliterator.MODE_MAP_LAST)); + checkSpliterator("double", DoubleStreamEx.of(doubles, 0, doubles.length - 1).boxed().append(doubles[doubles.length - 1] + 2).toList(), + () -> new PairSpliterator.PSOfDouble((a, b) -> a, a -> a + 2, Arrays.spliterator(doubles), PairSpliterator.MODE_MAP_LAST)); }); } diff --git a/src/test/java/one/util/streamex/PrependSpliteratorTest.java b/src/test/java/one/util/streamex/PrependSpliteratorTest.java index 49800f91..c0b7edc8 100644 --- a/src/test/java/one/util/streamex/PrependSpliteratorTest.java +++ b/src/test/java/one/util/streamex/PrependSpliteratorTest.java @@ -48,7 +48,7 @@ public void testSpliterator() { .estimateSize()); PrependSpliterator spltr = new PrependSpliterator<>(IntStream.range(1, 100).spliterator(), 0); - spltr.tryAdvance(x -> assertEquals(0, (int)x)); + spltr.tryAdvance(x -> assertEquals(0, (int) x)); assertTrue(spltr.hasCharacteristics(Spliterator.SORTED)); } } diff --git a/src/test/java/one/util/streamex/StreamExHeadTailTest.java b/src/test/java/one/util/streamex/StreamExHeadTailTest.java index 31bf2688..49cc91cc 100644 --- a/src/test/java/one/util/streamex/StreamExHeadTailTest.java +++ b/src/test/java/one/util/streamex/StreamExHeadTailTest.java @@ -194,7 +194,7 @@ private static StreamEx cycleTSO(StreamEx input, int n, List buf) { return input.headTail((head, tail) -> { buf.add(head); return cycleTSO(tail, n, buf).prepend(head); - }, () -> IntStreamEx.range(n-1).flatMapToObj(i -> buf.stream())); + }, () -> IntStreamEx.range(n - 1).flatMapToObj(i -> buf.stream())); } // mapFirst (TSO) @@ -300,7 +300,8 @@ static StreamEx twoFilters(StreamEx input, Predicate f1, Predicate< private static StreamEx twoFilters(StreamEx input, Predicate f1, Predicate f2, Stream.Builder buf) { return input.headTail((head, tail) -> { StreamEx res = twoFilters(tail, f1, f2, buf); - if(f2.test(head)) buf.add(head); + if (f2.test(head)) + buf.add(head); return f1.test(head) ? res.prepend(head) : res; }, buf::build); } @@ -443,9 +444,9 @@ public void testHeadTailRecursive() { assertEquals(asList("1. Foo", "2. Bar", "3. Baz"), withIndices(StreamEx.of("Foo", "Bar", "Baz"), (idx, e) -> (idx + 1) + ". " + e).toList()); - - assertEquals(asList(1,2,3,4,10), appendSum(StreamEx.of(1,2,3,4)).toList()); - assertFalse(appendSum(StreamEx.of(1,2,3,4)).has(11)); + + assertEquals(asList(1, 2, 3, 4, 10), appendSum(StreamEx.of(1, 2, 3, 4)).toList()); + assertFalse(appendSum(StreamEx.of(1, 2, 3, 4)).has(11)); assertEquals(asList(0, 3, 6, 9, 12, 15, 18, 0, 4, 8, 12, 16), twoFilters(IntStreamEx.range(20).boxed(), x -> x % 3 == 0, x -> x % 4 == 0).toList()); @@ -454,8 +455,8 @@ public void testHeadTailRecursive() { assertEquals(asList(0, 3, 6, 9, 12, 15, 18), every3(IntStreamEx.range(20).boxed()).toList()); //noinspection RedundantTypeArguments -- necessary for Javac 8u92 - assertEquals(asList(0, 1, 2, 3, 3), StreamEx.of(0, 1, 4, 2, 10, 3, 5, 10, 3, 15).chain( - limitSorted(Comparator. naturalOrder(), 5)).toList()); + assertEquals(asList(0, 1, 2, 3, 3), + StreamEx.of(0, 1, 4, 2, 10, 3, 5, 10, 3, 15).chain(limitSorted(Comparator.naturalOrder(), 5)).toList()); assertEquals(asList(1, 3, 7, 9, 2, 4, 11, 17, 5, 10), StreamEx.of(1, 3, 5, 7, 9, 2, 4, 10, 11, 17).chain(moveToEnd(x -> x % 5 == 0)).toList()); @@ -536,7 +537,7 @@ public void testHeadTailClose() { assertTrue(internalClosed.get()); assertTrue(finalClosed.get()); - res = StreamEx. empty().headTail((head, tail) -> tail); + res = StreamEx.empty().headTail((head, tail) -> tail); assertEquals(0, res.count()); res.close(); } @@ -566,16 +567,16 @@ public void testHeadTailSimple() { @Test public void testSpliterator() { - Spliterator spltr = map(StreamEx.of(1,2,3,4), x -> x*2).spliterator(); + Spliterator spltr = map(StreamEx.of(1, 2, 3, 4), x -> x * 2).spliterator(); assertTrue(spltr.hasCharacteristics(Spliterator.ORDERED)); assertEquals(4, spltr.estimateSize()); - assertTrue(spltr.tryAdvance(x -> assertEquals(2, (int)x))); + assertTrue(spltr.tryAdvance(x -> assertEquals(2, (int) x))); assertEquals(3, spltr.estimateSize()); - assertTrue(spltr.tryAdvance(x -> assertEquals(4, (int)x))); + assertTrue(spltr.tryAdvance(x -> assertEquals(4, (int) x))); assertEquals(2, spltr.estimateSize()); - assertTrue(spltr.tryAdvance(x -> assertEquals(6, (int)x))); + assertTrue(spltr.tryAdvance(x -> assertEquals(6, (int) x))); assertEquals(1, spltr.estimateSize()); - assertTrue(spltr.tryAdvance(x -> assertEquals(8, (int)x))); + assertTrue(spltr.tryAdvance(x -> assertEquals(8, (int) x))); assertFalse(spltr.tryAdvance(x -> fail("Should not be called"))); assertEquals(0, spltr.estimateSize()); } diff --git a/src/test/java/one/util/streamex/StreamExTest.java b/src/test/java/one/util/streamex/StreamExTest.java index 7b40ed7f..9b497bbe 100644 --- a/src/test/java/one/util/streamex/StreamExTest.java +++ b/src/test/java/one/util/streamex/StreamExTest.java @@ -435,7 +435,7 @@ public void testSelect() { .length() == 1).toList()); StringBuilder sb = new StringBuilder(); StringBuffer sbb = new StringBuffer(); - StreamEx. of("test", sb, sbb).select(Appendable.class).forEach(a -> { + StreamEx.of("test", sb, sbb).select(Appendable.class).forEach(a -> { try { a.append("b"); } catch (IOException e) { @@ -579,7 +579,7 @@ public void testMinMax() { assertEquals(supplier.toString(), minStr, supplier.get().minByDouble(String::length).get()); assertEquals(supplier.toString(), minStr, supplier.get().minBy(String::length).get()); }); - assertFalse(StreamEx. empty().minByInt(String::length).isPresent()); + assertFalse(StreamEx.empty().minByInt(String::length).isPresent()); }); } @@ -781,8 +781,8 @@ static class Point { @Test public void testPairMap() { - assertEquals(0, StreamEx. empty().pairMap(String::concat).count()); - assertArrayEquals(new Object[0], StreamEx. empty().pairMap(String::concat).toArray()); + assertEquals(0, StreamEx.empty().pairMap(String::concat).count()); + assertArrayEquals(new Object[0], StreamEx.empty().pairMap(String::concat).toArray()); assertEquals(0, StreamEx.of("a").pairMap(String::concat).count()); assertEquals(asList("aa", "aa", "aa"), StreamEx.generate(() -> "a").pairMap(String::concat).limit(3).toList()); AtomicBoolean flag = new AtomicBoolean(); @@ -820,7 +820,7 @@ public void testPairMap() { // Find first element which violates the sorting assertEquals("bba", firstMisplaced(asList("a", "bb", "bb", "bba", "bb", "c")).get()); assertFalse(firstMisplaced(asList("a", "bb", "bb", "bb", "c")).isPresent()); - assertFalse(firstMisplaced(Arrays. asList()).isPresent()); + assertFalse(firstMisplaced(Arrays.asList()).isPresent()); assertFalse(IntStreamEx.range(1000).greater(2000).boxed().parallel().pairMap((a, b) -> a).findFirst() .isPresent()); } @@ -1565,7 +1565,7 @@ public void testDropWhile() { @Test public void testTakeDropUnordered() { repeat(10, n -> withRandom(rnd -> { - List data = IntStreamEx.of(rnd, n*100, 0, rnd.nextInt(10)+2).mapToObj(x -> x != 0).toList(); + List data = IntStreamEx.of(rnd, n * 100, 0, rnd.nextInt(10) + 2).mapToObj(x -> x != 0).toList(); List sorted = StreamEx.of(data).sorted().toList(); streamEx(() -> data.stream().unordered(), s -> { assertFalse(StreamEx.of(s.get().takeWhile(b -> b).toList()).has(false)); @@ -1647,7 +1647,7 @@ public void testCartesianReduce() { streamEx(() -> StreamEx.cartesianProduct(input3, "", (a, b) -> a + b), supplier -> assertEquals( "134,135,234,235", supplier.get().joining(","))); - assertEquals(asList(""), StreamEx.cartesianProduct(Collections.> emptyList(), "", String::concat) + assertEquals(asList(""), StreamEx.cartesianProduct(Collections.>emptyList(), "", String::concat) .toList()); assertEquals(asList(""), StreamEx.cartesianPower(0, asList(1, 2, 3), "", (a, b) -> a + b).toList()); } @@ -2087,20 +2087,20 @@ public void testIntersperse() { @Test public void testIfEmpty() { - repeat(10, n -> streamEx(asList(1,2,3,4,5,6)::stream, s -> { - assertEquals("123456", s.get().ifEmpty(7,8,9).joining()); - assertEquals("123456", s.get().filter(x -> x > 0).ifEmpty(7,8,9).joining()); - assertEquals("6", s.get().filter(x -> x > 5).ifEmpty(7,8,9).joining()); - assertEquals("789", s.get().filter(x -> x < 0).ifEmpty(7,8,9).joining()); + repeat(10, n -> streamEx(asList(1, 2, 3, 4, 5, 6)::stream, s -> { + assertEquals("123456", s.get().ifEmpty(7, 8, 9).joining()); + assertEquals("123456", s.get().filter(x -> x > 0).ifEmpty(7, 8, 9).joining()); + assertEquals("6", s.get().filter(x -> x > 5).ifEmpty(7, 8, 9).joining()); + assertEquals("789", s.get().filter(x -> x < 0).ifEmpty(7, 8, 9).joining()); assertEquals("123456", s.get().ifEmpty(s.get()).joining()); assertEquals("123456", s.get().filter(x -> x > 0).ifEmpty(s.get().filter(x -> x % 2 == 1)).joining()); assertEquals("135", s.get().filter(x -> x < 0).ifEmpty(s.get().filter(x -> x % 2 == 1)).joining()); assertEquals("", s.get().filter(x -> x < 0).ifEmpty(s.get().filter(x -> x < 0)).joining()); - assertEquals(Optional.of(1), s.get().ifEmpty(7,8,9).findFirst()); - assertEquals(Optional.of(1), s.get().filter(x -> x > 0).ifEmpty(7,8,9).findFirst()); - assertEquals(Optional.of(6), s.get().filter(x -> x > 5).ifEmpty(7,8,9).findFirst()); - assertEquals(Optional.of(7), s.get().filter(x -> x < 0).ifEmpty(7,8,9).findFirst()); + assertEquals(Optional.of(1), s.get().ifEmpty(7, 8, 9).findFirst()); + assertEquals(Optional.of(1), s.get().filter(x -> x > 0).ifEmpty(7, 8, 9).findFirst()); + assertEquals(Optional.of(6), s.get().filter(x -> x > 5).ifEmpty(7, 8, 9).findFirst()); + assertEquals(Optional.of(7), s.get().filter(x -> x < 0).ifEmpty(7, 8, 9).findFirst()); assertEquals(Optional.of(1), s.get().ifEmpty(s.get()).findFirst()); assertEquals(Optional.of(1), s.get().filter(x -> x > 0).ifEmpty(s.get().filter(x -> x % 2 == 1)).findFirst()); assertEquals(Optional.of(1), s.get().filter(x -> x < 0).ifEmpty(s.get().filter(x -> x % 2 == 1)).findFirst()); diff --git a/src/test/java/one/util/streamex/TailConcatSpliteratorTest.java b/src/test/java/one/util/streamex/TailConcatSpliteratorTest.java index c09ef908..721bb136 100644 --- a/src/test/java/one/util/streamex/TailConcatSpliteratorTest.java +++ b/src/test/java/one/util/streamex/TailConcatSpliteratorTest.java @@ -42,13 +42,13 @@ public void testCharacteristics() { spltr = new TailConcatSpliterator<>(Spliterators.emptySpliterator(), Spliterators.emptySpliterator()); assertTrue(spltr.hasCharacteristics(Spliterator.SIZED)); assertEquals(0, spltr.getExactSizeIfKnown()); - - spltr = new TailConcatSpliterator<>(IntStreamEx.range(1000).spliterator(), new HashSet<>(Arrays.asList(1,2,3)).spliterator()); + + spltr = new TailConcatSpliterator<>(IntStreamEx.range(1000).spliterator(), new HashSet<>(Arrays.asList(1, 2, 3)).spliterator()); assertTrue(spltr.hasCharacteristics(Spliterator.SIZED)); assertFalse(spltr.hasCharacteristics(Spliterator.SUBSIZED)); assertFalse(spltr.hasCharacteristics(Spliterator.ORDERED)); assertEquals(1003, spltr.getExactSizeIfKnown()); - spltr.tryAdvance(x -> assertEquals(0, (int)x)); + spltr.tryAdvance(x -> assertEquals(0, (int) x)); assertEquals(1002, spltr.getExactSizeIfKnown()); TailConcatSpliterator longSpltr = new TailConcatSpliterator<>(LongStreamEx.range(Long.MAX_VALUE / 2 + 1) @@ -57,15 +57,15 @@ public void testCharacteristics() { assertFalse(longSpltr.hasCharacteristics(Spliterator.SUBSIZED)); assertTrue(longSpltr.hasCharacteristics(Spliterator.ORDERED)); assertEquals(Long.MAX_VALUE, longSpltr.estimateSize()); - longSpltr.tryAdvance(x -> assertEquals(0L, (long)x)); + longSpltr.tryAdvance(x -> assertEquals(0L, (long) x)); assertEquals(Long.MAX_VALUE, longSpltr.estimateSize()); Queue q = new ConcurrentLinkedDeque<>(); spltr = new TailConcatSpliterator<>(q.spliterator(), q.spliterator()); q.add(1); assertFalse(longSpltr.hasCharacteristics(Spliterator.SIZED)); - assertTrue(spltr.tryAdvance(x -> assertEquals(1, (int)x))); - assertTrue(spltr.tryAdvance(x -> assertEquals(1, (int)x))); + assertTrue(spltr.tryAdvance(x -> assertEquals(1, (int) x))); + assertTrue(spltr.tryAdvance(x -> assertEquals(1, (int) x))); assertFalse(spltr.tryAdvance(x -> fail("Should not happen"))); } } diff --git a/src/test/java/one/util/streamex/TestHelpers.java b/src/test/java/one/util/streamex/TestHelpers.java index 4a750ca3..65166ed0 100644 --- a/src/test/java/one/util/streamex/TestHelpers.java +++ b/src/test/java/one/util/streamex/TestHelpers.java @@ -85,7 +85,7 @@ public StreamExSupplier(Supplier> base, Mode mode) { @Override public StreamEx get() { - if(mode == Mode.SPLITERATOR) + if (mode == Mode.SPLITERATOR) return StreamEx.of(base.get().spliterator()); return StreamEx.of(super.get()); } @@ -127,7 +127,7 @@ static void withRandom(Consumer cons) { */ static void withRandom(long seed, Consumer cons) { Random random = new Random(seed); - withMessage("Using new Random("+seed+")", () -> cons.accept(random)); + withMessage("Using new Random(" + seed + ")", () -> cons.accept(random)); } /** @@ -286,7 +286,7 @@ static void checkSpliterator(String msg, List expected, Supplier forCharacteristics = supplier.get(); - if(forCharacteristics.hasCharacteristics(Spliterator.SORTED)) { + if (forCharacteristics.hasCharacteristics(Spliterator.SORTED)) { forCharacteristics.getComparator(); // must not fail } assertTrue(forCharacteristics.estimateSize() >= 0); @@ -319,13 +319,13 @@ static void checkSpliterator(String msg, List expected, Supplier void checkSpliterator(String msg, List expected, Supplier void checkSpliterator(String msg, List expected, Supplier> results = StreamEx.> generate(ArrayList::new).limit(spliterators.size()) + List> results = StreamEx.>generate(ArrayList::new).limit(spliterators.size()) .toList(); int count = spliterators.size(); while (count > 0) { diff --git a/src/test/java/one/util/streamex/WithFirstSpliteratorTest.java b/src/test/java/one/util/streamex/WithFirstSpliteratorTest.java index 01b80d1f..6a5907c3 100644 --- a/src/test/java/one/util/streamex/WithFirstSpliteratorTest.java +++ b/src/test/java/one/util/streamex/WithFirstSpliteratorTest.java @@ -45,9 +45,9 @@ public void testCharacteristics() { .spliterator(), Integer::sum); assertTrue(spltr.hasCharacteristics(Spliterator.SIZED)); assertEquals(6, spltr.getExactSizeIfKnown()); - assertTrue(spltr.tryAdvance(x -> assertEquals(12, (int)x))); + assertTrue(spltr.tryAdvance(x -> assertEquals(12, (int) x))); assertEquals(5, spltr.getExactSizeIfKnown()); - assertTrue(spltr.tryAdvance(x -> assertEquals(7, (int)x))); + assertTrue(spltr.tryAdvance(x -> assertEquals(7, (int) x))); assertEquals(4, spltr.getExactSizeIfKnown()); spltr = new WithFirstSpliterator<>(Spliterators.emptySpliterator(), Integer::sum); @@ -60,8 +60,8 @@ public void testCharacteristics() { .spliterator(), Long::sum); assertTrue(longSpltr.hasCharacteristics(Spliterator.SIZED)); assertEquals(Long.MAX_VALUE, longSpltr.getExactSizeIfKnown()); - assertTrue(longSpltr.tryAdvance(x -> assertEquals(0, (long)x))); - assertEquals(Long.MAX_VALUE-1, longSpltr.getExactSizeIfKnown()); + assertTrue(longSpltr.tryAdvance(x -> assertEquals(0, (long) x))); + assertEquals(Long.MAX_VALUE - 1, longSpltr.getExactSizeIfKnown()); longSpltr = new WithFirstSpliterator<>(LongStreamEx.range(-1, Long.MAX_VALUE) .spliterator(), Long::sum); diff --git a/src/test/java/one/util/streamex/ZipSpliteratorTest.java b/src/test/java/one/util/streamex/ZipSpliteratorTest.java index 00cd86ad..973b92dc 100644 --- a/src/test/java/one/util/streamex/ZipSpliteratorTest.java +++ b/src/test/java/one/util/streamex/ZipSpliteratorTest.java @@ -30,34 +30,34 @@ public class ZipSpliteratorTest { @Test public void testEven() { - List expected = IntStreamEx.range(200).mapToObj(x -> x+":"+(x+1)).toList(); + List expected = IntStreamEx.range(200).mapToObj(x -> x + ":" + (x + 1)).toList(); int[] nums = IntStreamEx.range(200).toArray(); - Supplier> s = () -> new ZipSpliterator<>(IntStreamEx.range(200).spliterator(), - IntStreamEx.range(1, 201).spliterator(), (x, y) -> x+":"+y, true); + Supplier> s = () -> new ZipSpliterator<>(IntStreamEx.range(200).spliterator(), + IntStreamEx.range(1, 201).spliterator(), (x, y) -> x + ":" + y, true); checkSpliterator("even", expected, s); - s = () -> new ZipSpliterator<>(IntStreamEx.range(200).spliterator(), - IntStreamEx.range(2, 202).parallel().map(x -> x - 1).spliterator(), (x, y) -> x+":"+y, true); + s = () -> new ZipSpliterator<>(IntStreamEx.range(200).spliterator(), + IntStreamEx.range(2, 202).parallel().map(x -> x - 1).spliterator(), (x, y) -> x + ":" + y, true); checkSpliterator("evenMap", expected, s); - s = () -> new ZipSpliterator<>(IntStreamEx.of(nums).spliterator(), - IntStreamEx.range(2, 202).parallel().map(x -> x - 1).spliterator(), (x, y) -> x+":"+y, true); + s = () -> new ZipSpliterator<>(IntStreamEx.of(nums).spliterator(), + IntStreamEx.range(2, 202).parallel().map(x -> x - 1).spliterator(), (x, y) -> x + ":" + y, true); checkSpliterator("evenArray", expected, s); } @Test public void testUnEven() { - List expected = IntStreamEx.range(200).mapToObj(x -> x+":"+(x+1)).toList(); + List expected = IntStreamEx.range(200).mapToObj(x -> x + ":" + (x + 1)).toList(); Supplier> s = () -> new ZipSpliterator<>(IntStreamEx.range(200).spliterator(), - IntStreamEx.range(90).append(IntStreamEx.range(90, 200)).spliterator(), (x, y) -> x+":"+(y+1), true); + IntStreamEx.range(90).append(IntStreamEx.range(90, 200)).spliterator(), (x, y) -> x + ":" + (y + 1), true); checkSpliterator("unevenRight", expected, s); - s = () -> new ZipSpliterator<>( - IntStreamEx.range(90).append(IntStreamEx.range(90, 200)).spliterator(), - IntStreamEx.range(200).spliterator(), (x, y) -> x+":"+(y+1), true); + s = () -> new ZipSpliterator<>( + IntStreamEx.range(90).append(IntStreamEx.range(90, 200)).spliterator(), + IntStreamEx.range(200).spliterator(), (x, y) -> x + ":" + (y + 1), true); checkSpliterator("unevenLeft", expected, s); } @Test public void testUnknownSize() { - List expected = IntStreamEx.range(200).mapToObj(x -> x+":"+(x+1)).toList(); + List expected = IntStreamEx.range(200).mapToObj(x -> x + ":" + (x + 1)).toList(); Supplier> s = () -> new ZipSpliterator<>(Spliterators.spliteratorUnknownSize(IntStreamEx .range(200).iterator(), Spliterator.ORDERED), Spliterators.spliteratorUnknownSize(IntStreamEx.range(1, 201).iterator(), Spliterator.ORDERED), (x, y) -> x + ":" + y, true); diff --git a/src/test/java/one/util/streamex/api/StreamExApiTest.java b/src/test/java/one/util/streamex/api/StreamExApiTest.java index 86c0a48b..753c214f 100644 --- a/src/test/java/one/util/streamex/api/StreamExApiTest.java +++ b/src/test/java/one/util/streamex/api/StreamExApiTest.java @@ -33,8 +33,7 @@ public class StreamExApiTest { @Test public void testMap() { BiFunction, Function, StreamEx> streamMapper = StreamEx::map; - assertEquals(asList(2, 4, 10), - streamMapper.apply(StreamEx.of(1, 2, 5), x -> x * 2).toList()); + assertEquals(asList(2, 4, 10), streamMapper.apply(StreamEx.of(1, 2, 5), x -> x * 2).toList()); } @Test diff --git a/CHANGES.md b/wiki/CHANGES.md similarity index 98% rename from CHANGES.md rename to wiki/CHANGES.md index b7b6c810..5b193d59 100644 --- a/CHANGES.md +++ b/wiki/CHANGES.md @@ -1,335 +1,335 @@ -# StreamEx changes - -Check also [MIGRATION.md](MIGRATION.md) for possible compatibility problems. - -### 0.7.3 -* [#028]: Added: `StreamEx.toCollectionAndThen` - -### 0.7.2 -* Fixed: accidental use of Java 9 API in CrossSpliterator - -### 0.7.1 -* [#202] Fixed: `StreamEx/EntryStream.ofTree` stack consumption is now limited -* Multi-release Jar is used to provide Java 9+ specializations - -### 0.7.0 -* [#193] Removed optimizations which rely on internal implementation details of Stream API (unwrap IteratorSpliterator; - do not delegate to Stream::close when unnecessary) -* [#194] Removed: `skipOrdered`. -* [#200] Added: `EntryStream.allMatch/anyMatch/noneMatch` accepting key-value pair. -* Now Java 11 is used to build the library. In particular this results in modern JavaDoc artifact (including the search). - -### 0.6.8 -* [#183] Added: `StreamEx.mapPartial`, `EntryStream.mapToKeyPartial/mapToValuePartial/mapKeyValuePartial` -* [#191] Deprecated: `skipOrdered`. - -### 0.6.7 -* [#76] Added: `StreamEx.zipWith` accepting `BaseStream` (so zipWith(IntStreamEx.ints()) works) -* [#131] Added: `StreamEx.ofCombinations` -* [#164] Added: `Joining.maxElements` -* [#179] Added: `MoreCollectors.onlyOne(Predicate)` - -### 0.6.6 -* [#145] Added: `intersperse` method for all stream types. -* [#144] Added: `EntryStream.generate` -* [#162] Added: `StreamEx.ifEmpty`, `EntryStream.ifEmpty` - -### 0.6.5 -* [#137] Added: `StreamEx.toNavigableMap()`, `EntryStream.toNavigableMap()` -* [#141] Added: `StreamEx.flatArray()`, `EntryStream.flatArray()` -* [#143] Optimized: `AbstractStreamEx.takeWhile/takeWhileInclusive/dropWhile` for parallel unordered case. - -### 0.6.4 -* [#132] Fixed: `StreamEx.parallel(fjp)` does not parallelize underlying Java Stream if it already exists -* [#127] Added: `StreamEx.filterBy` -* [#128] Added: `EntryStream.prefixKeys`, `EntryStream.prefixValues` -* [#135] Added: `StreamEx.removeBy` - -### 0.6.3 - -* [#111] Added: `StreamEx.toArray(elementClass)` -* [#112] Added: `StreamEx.toArray(emptyArray)` -* [#116] Added: `MoreCollectors.ifAllMatch()` -* [#119] Added: `AbstractStreamEx.toImmutableList()`, `AbstractStreamEx.toImmutableSet()`, `EntryStream.toImmutableMap()` -* [#123] Added: `StreamEx.into(collection)`, `EntryStream.into(map)` - -### 0.6.2 - -* [#17] Optimized: `StreamEx.ofTree`, `EntryStream.ofTree`. -* [#104] Added: `StreamEx.ofReversed()`. -* [#105] Added: `MoreCollectors.minMax()`. -* [#108] Added: `IntStreamEx.of(IntBuffer)`, `LongStreamEx.of(LongBuffer)`, `DoubleStreamEx.of(DoubleBuffer)`. - -### 0.6.1 - -* [#90] Changed: `AbstractStreamEx` class (which shares common functionality of `StreamEx` and `EntryStream`) is public now. -* [#92] Added: `IntStreamEx.of(InputStream)`. -* [#93] Added: `IntStreamEx.asByteInputStream()`. -* [#94] Added: `prefix` method for all stream types. - -### 0.6.0 -Warning: this release introduces some changes which may break backwards compatibility. - -* [#67] Changed: `StreamEx.withFirst()` now includes `(first, first)` pair into result as well. If you want to exclude it, use `.withFirst().skip(1)`. -* [#70] Fixed: `MoreCollectors.least()/greatest()` now support null element (if the supplied `Comparator` supports nulls). -* [#70] Fixed: `MoreCollectors.least()/greatest()` now returns stable result (the order of equal elements is not changed). -* [#70] Optimized: `MoreCollectors.least()/greatest()` is usually faster now, especially when the selected elements are close to the stream end. -* [#74] Added: `EntryStream.removeKeyValue()`. -* [#77] Added: `MoreCollectors.filtering()/mapping()/flatMapping()` with default downstream Collector `toList()`. -* [#79] Added: `iterate(seed, predicate, op)` for all stream types. -* [#82] Added: `Emitter` class and primitive friends to create non-trivial stream sources. -* [#83] Changed: `StreamEx.of(Collection)`, `of(Iterator)`, etc. now use `? extends T` type instead of just `T`. -* [#85] Added: `StreamEx.mapFirstOrElse()/mapLastOrElse()`. -* [#86] Added: `peekFirst()`, `peekLast()` for all stream types. -* [#89] Added: `produce()` method for all stream types. -* Updated documentation. - -### 0.5.5 -* [#41] Added: `IntStreamEx/LongStreamEx/StreamEx.without()` accepting several elements. -* [#60] Added: `StreamEx.zipWith()` to zip the stream with another. -* [#63] Optimized `IntStreamEx/LongStreamEx/DoubleStreamEx.reverseSorted()`: much faster now and take less memory. -* [#64] Added: `EntryStream.toMapAndThen()`. -* [#66] Added: `takeWhileInclusive()` for all stream types. -* [#71] Fixed: some collectors like `head(0)`, `greatest(0)` failed when using with JDK Stream. -* [#72] Added: `IntStreamEx.ints()` and `LongStreamEx.longs()`. -* [#73] Added: `EntryStream.collapseKeys()`. - -### 0.5.4 -* [#10] Added: `chain()` method to all stream types allowing fluently chaining custom operations. -* [#55] TailConcatSpliterator implemented; now all `StreamEx/EntryStream.append/prepend` methods are TSO-compatible. -* [#56] Fixed: `StreamEx.append/prepend(Collection)` and `EntryStream.append/prepend(Map)` now properly append/prepend if supplied collection is concurrent (so it may be legally modified during the subsequent operations). -* [#57] JDK Stream creation is deferred until necessary. Now quasi-intermediate operations and especially `headTail()` may work faster. -* [#59] Added: `StreamEx.prepend(value)`, `StreamEx.append(value)` which might work faster than existing var-args methods. -* Updated documentation. - -### 0.5.3 -* [#50] Added: `StreamEx.withFirst()`: extract first stream element -* [#51] Fixed: `StreamEx.parallel(fjp).runLengths()` fails to run the task in the specified pool. -* [#52] `StreamEx.append(T...)` and `prepend(T...)` are declared as @SafeVarargs and final now. -* [#53] Optimized: `mapFirst`/`mapLast` methods will have less overhead now, especially for primitive streams. -* [#54] Added: `StreamEx.headTail()`: map to the new stream using the first stream element and the stream of the rest elements. - -### 0.5.2 -* [#3] Optimized: parallel performance of `StreamEx.ofLines` as well as `StreamEx.split` -* [#19] Optimized: pairMap and forPairs may work faster now, especially in the presence of upstream intermediate operations. -* [#42] Added: `EntryStream.ofTree` methods to stream the tree-like structure tracking nodes depth. -* [#46] Optimized: parallel performance of all `of(Iterator)` methods. -* [#47] Added: `EntryStream.flatMapToKey/flatMapToValue` methods. -* [#48] `EntryStream.of(key, value, key, value...)` now accepts up to 10 pairs. -* Fixed: `StreamEx.of(emptyList().iterator()).parallel()` failed with `NoSuchElementException`. - -### 0.5.1 - -* [#13] Added: `StreamEx.split` to split with single character delimiter. -* [#28] Updated: now `StreamEx.select`, `EntryStream.selectKeys` and `EntryStream.selectValues` accept any type (not necessarily the subtype of current element). -* [#32] Added: `MoreCollectors.dominators` collector which collects the elements to the list leaving only "dominators". -* [#33] Updated: `StreamEx.split("", pattern)` now returns stream of single `""` string instead of empty stream. -* [#35] Added: construction of all stream types from the `Iterator`. -* [#36] Added: `StreamEx.of(Enumeration)` static method. -* [#38] Added: `scanLeft` for primitive streams. -* Updated documentation. - -### 0.5.0 - -Warning: this release introduces some changes which break the backward compatibility and will require the changes in source code if you used the previous StreamEx versions. - -* The package `javax.util.streamex` is renamed to `one.util.streamex`. Every occurrence of `javax.util.streamex` in source files must be replaced with `one.util.streamex`. -* The OSGi Bundle-SymbolicName is changed from `javax.util.streamex` to `one.util.streamex`. -* The Maven groupID is changed from `io.github.amaembo` to `one.util`. Dependencies in pom.xml files should be updated accordingly. -* Added: `StreamEx.ofLines(Path)` and `StreamEx.ofLines(Path, Charset)` -* Added: `MoreCollectors.commonPrefix()/commonSuffix()` short-circuiting collectors. -* Added: `IntStreamEx.of(Integer[])`, `LongStreamEx.of(Long[])`, `DoubleStreamEx.of(Double[])` static methods. -* Deprecated methods `StreamEx.ofEntries()` removed. -* Deprecated methods `collectingAndThen` in primitive collectors removed (use `andThen()` instead). -* Updated documentation. - -### 0.4.1 - -* Added: `StreamEx/IntStreamEx/LongStreamEx/DoubleStreamEx.mapLast/mapFirst` methods. -* Added: `MoreCollectors.flatMapping` collector. -* Added: `Joining` collector: an advanced version of `Collectors.joining` which may short-circuit. -* Fixed: `StreamEx.cross(mapper)` now correctly handles the case when mapper returns null instead of empty stream. -* Optimized: ordered stateful short-circuit collectors now may process less elements in parallel. -* Optimized: `StreamEx/EntryStream.toList()/toListAndThen()/foldRight()/scanRight()` now faster, especially for sized stream. -* Optimized: collapse-based operations like `StreamEx.collapse/groupRuns/runLengths/intervalMap` now may work faster, -especially when stream has more intermediate operations before them. -* Updated documentation. - -### 0.4.0 - -* Introduced the concept of short-circuiting collectors. -* `StreamEx/EntryStream.collect(Collector)` method works as short-circuit operation if short-circuiting collector is passed. -* `MoreCollectors.first/head` collectors are short-circuiting now. -* `MoreCollectors.groupingByEnum` collector may short-circuit if downstream collector is short-circuiting. -* `MoreCollectors.pairing` collector may short-circuit if both downstream collectors are short-circuiting. -* Added new short-circuiting collectors: `onlyOne`, `intersecting`, `toEnumSet`, `andingInt`, `andingLong`. -* Added new collectors: `filtering`, `groupingBy` (with domain specification) which short-circuit when downstream collector is short-circuiting. -* Added collectors `mapping`, `collectingAndThen`, `partitioningBy` which mimic standard JDK collectors, but short-circuit when downstream collector is short-circuiting. -* Added `indexOf` methods for all stream types. -* Added `StreamEx/EntryStream.foldLeft/foldRight` methods without identity argument. -* Added `StreamEx/EntryStream.scanLeft/scanRight` methods without identity argument. -* Added `StreamEx.cartesianProduct/cartesianPower` methods with reduction operator. -* Added `IntStreamEx/LongStreamEx.range/rangeClosed` methods with additional step parameter. -* Added `IntStreamEx/LongStreamEx/DoubleStreamEx.foldLeft` methods. -* Methods `StreamEx/EntryStream.toMap/toSortedMap/toCustomMap` without merge function now produce better exception message in the case of duplicate keys. -* Methods `StreamEx/EntryStream.toMap/toSortedMap/toCustomMap` accepting merge function are not guaranteed to return ConcurrentMap for parallel streams now. They however guarantee now the correct merging order for non-commutative merger functions. -* Methods `StreamEx/EntryStream.grouping*` are not guaranteed to return the ConcurrentMap for parallel streams now. They however guarantee now the correct order of downstream collection. -* Methods `StreamEx.ofEntries` are declared as deprecated and may be removed in future releases! -* Deprecated methods `EntryStream.mapEntryKeys`/`mapEntryValues` are removed! -* Updated documentation - -### 0.3.8 - -* Added `toBooleanArray` collectors (object and primitive). -* Added `MoreCollectors.distinctBy` collector. -* Added `StreamEx/EntryStream.distinct(keyExtractor)` intermediate operation. -* Added `EntryStream.distinctKeys/distinctValues` intermediate operations. -* Added `StreamEx.cartesianPower/cartesianProduct` static methods. -* Optimized: `MoreCollectors.least/greatest` collectors are now much faster (up to 10x depending on input). -* Updated documentation - -### 0.3.7 - -* Added `MoreCollectors.groupingByEnum` collector. -* Added `IntCollector/LongCollector/DoubleCollector.averaging` primitive collectors. -* Added `IntCollector/LongCollector/DoubleCollector.andThen` default methods to replace `collectingAndThen`. -* Added `StreamEx.toFlatCollection` and `StreamEx.toFlatList` terminal operations. -* Added `StreamEx.ofSubLists(list, length, shift)` static method. -* Methods `IntCollector/LongCollector/DoubleCollector.collectingAndThen` are declared as deprecated and may be removed in future releases! -* Updated documentation - -### 0.3.6 - -* Added `StreamEx.collapse(Predicate, Collector)` operation. -* Added `takeWhile` and `dropWhile` methods for all stream types. -* Added `StreamEx.ofPairs` and `EntryStream.ofPairs` methods. -* Optimized: `minBy*/maxBy*` methods for primitive streams now call keyExtractor function at most once per element. -* Updated documentation - -### 0.3.5 - -* Generic arguments relaxed for `StreamEx` methods: `forPairs`, `collapse`, `groupRuns`, `intervalMap`, `sortedBy`. -* Added `MoreCollectors.minIndex/maxIndex` collectors. - -### 0.3.4 - -* Fixed: `EntryStream.of(List)`, `EntryStream.of(T[])` and `StreamEx.runLengths` returned stream -of `Map.Entry` objects which violate the documented contract for `equals` and `hashCode`. -* Fixed: `pairMap` method for all streams worked incorrectly when previous steps included `parallel().flatMap()` due to JDK bug. New version may also work faster in parallel for certain sources. -* Fixed: `collapse`-based methods (`collapse`, `groupRuns`, `runLengths`, `intervalMap`) worked incorrectly in various cases in parallel mode. New version may also work faster in parallel for certain sources. -* Fixed: `minBy*/maxBy*` for primitive streams now return strictly the first matched element (not the arbitrary one). -* Optimized: `minBy/maxBy` methods for primitive streams now call keyExtractor function at most once per element -* Optimized: many stream creation methods (`zip` for all streams, `EntryStream.of(List)`, `StreamEx.ofSubLists`, etc.) now use custom spliterator. -* Optimized: `IntStreamEx.ofChars` reimplemented for JDK 8 as original `CharSequence.chars` implementation is poor. -* Added construction of all stream types from the `Spliterator`. -* Updated documentation - -### 0.3.3 - -* Added `StreamEx.intervalMap` method -* Added `StreamEx.runLengths` method -* Added `StreamEx.ofSubLists` method -* Added `MoreCollectors.countingInt` collector -* `StreamEx/EntryStream.maxBy*/minBy*` methods optimized: now keyExtractor function is called at most once per element -* `StreamEx.groupRuns` method optimized (up to 5x performance boost depending on data) -* `StreamEx.collapse` methods changed: now the elements passed to the predicate are guaranteed to be two adjacent elements from the source stream. -* Updated documentation: now documentation is automatically copied from JDK for the inherited methods. - -### 0.3.2 - -* Added `MoreCollectors` class: several useful collectors absent in JDK -* Added `skipOrdered(n)` method to every Stream implementation -* Updated documentation - -### 0.3.1 - -* Added `mapToEntry` method for primitive streams -* Added `joining` methods family for primitive streams -* Added `StreamEx.collapse`/`groupRuns` methods -* Added `StreamEx.distinct(atLeast)` method -* Released jar works now as an OSGi bundle -* Updated documentation - -### 0.3.0 - -* Added primitive collectors: `IntCollector`, `LongCollector`, `DoubleCollector` -* Added `flatMapToInt`/`flatMapToLong`/`flatMapToDouble`/`flatMapToObj` to primitive streams -* Added `EntryStream.flatMapKeyValue`/`filterKeyValue`/`mapToKey`/`mapToValue` methods -* Added `IntStreamEx.toCharArray`/`toShortArray`/`toByteArray` methods -* Added `DoubleStreamEx.toFloatArray` method -* Generic arguments for many methods are relaxed allowing more flexible usage -* Methods `EntryStream.mapEntryKeys`/`mapEntryValues` are declared as deprecated and may be removed in future releases! -* Updated documentation - -### 0.2.3 - -* Added `toListAndThen()`, `toSetAndThen()` methods to `StreamEx` and `EntryStream` -* Added `StreamEx.cross()` methods family -* Added `EntryStream.peekKeys()`, `EntryStream.peekValues()`, `EntryStream.peekKeyValue()` methods -* Added construction of `EntryStream` from `List` or array (indices are used as keys) -* Added construction of `EntryStream` from two and three key-value pairs -* Added `EntryStream.append`/`prepend` for two and three key-value pairs -* Added `greater`/`less`/`atLeast`/`atMost` filter methods for primitive streams -* Updated documentation - -### 0.2.2 - -* Fixed: `StreamEx.flatMapToEntry`, `EntryStream.flatMapKeys` and `EntryStream.flatMapValues` now correctly handles null value returned by mapper -* Added `StreamEx.scanRight()` and `EntryStream.scanRight()` methods -* Added `StreamEx.foldRight()` and `EntryStream.foldRight()` methods -* Added `StreamEx.forPairs()` method -* Added `StreamEx.partitioningBy()` methods -* Added `StreamEx.partitioningTo()` method -* Added `StreamEx.groupingTo()` methods -* Added `StreamEx.ofPermutations(int)` constructor -* Added `StreamEx.ofTree` constructors -* Added `StreamEx.without()`, `IntStreamEx.without()`, `LongStreamEx.without()` methods -* Added `EntryStream.join()` methods -* Updated documentation - -### 0.2.1 - -* Fixed: `flatCollection` method now correctly handles null value returned by mapper -* Added `IntStreamEx.charsToString`, `IntStreamEx.codePointsToString` methods -* Added `StreamEx.scanLeft()` and `EntryStream.scanLeft()` methods -* Added construction of `EntryStream` by zipping keys and values from two arrays/lists -* Added construction of `StreamEx`/`IntStreamEx`/`LongStreamEx`/`DoubleStreamEx` by zip-mapping two arrays/lists -* Added `pairMap` method for handling adjacent pairs -* The `append`/`prepend` methods of `StreamEx`/`EntryStream` can accept a `Collection` now -* Updated documentation - -### 0.2.0 - -* Added `parallel(fjc)` method for all stream types -* Added `StreamEx.reverseSorted()` method -* Added `StreamEx.foldLeft()` and `EntryStream.foldLeft()` methods -* Added `IntStreramEx.toBitSet()` method -* Added construction of `IntStreamEx` from `char[]`, `short[]`, `byte[]` arrays -* Added construction of `DoubleStreamEx` from `float[]` array -* Updated documentation - -### 0.1.2 - -* Added `IntStreamEx.elements` methods family -* Added construction of the constant stream -* Added `minBy`/`maxBy` methods family for primitive streams -* Updated documentation - -### 0.1.1 - -* Fixed: `empty()` method of all the streams worked incorrectly when used several times -* Added `IntStreamEx.ofIndices` methods family -* Added `IntStreamEx.range(int)` and `LongStreamEx.range(long)` -* Added `StreamEx.ofNullable` -* Added construction of the streams from optionals -* Added construction of the streams from array subrange -* Updated documentation - -### 0.1.0 - -Warning: this release introduces some changes which may break backwards compatibility - -* `EntryStream.toMap(Supplier)` and `EntryStream.toMap(BinaryOperator, Supplier)` renamed to `toCustomMap` -* Added `StreamEx.toSortedMap` and `EntryStream.toSortedMap` methods family -* Methods producing `Map` use concurrent collector for parallel streams if possible -* Updated documentation +# StreamEx changes + +Check also [MIGRATION.md](MIGRATION.md) for possible compatibility problems. + +### 0.7.3 +* [#028]: Added: `StreamEx.toCollectionAndThen` + +### 0.7.2 +* Fixed: accidental use of Java 9 API in CrossSpliterator + +### 0.7.1 +* [#202] Fixed: `StreamEx/EntryStream.ofTree` stack consumption is now limited +* Multi-release Jar is used to provide Java 9+ specializations + +### 0.7.0 +* [#193] Removed optimizations which rely on internal implementation details of Stream API (unwrap IteratorSpliterator; + do not delegate to Stream::close when unnecessary) +* [#194] Removed: `skipOrdered`. +* [#200] Added: `EntryStream.allMatch/anyMatch/noneMatch` accepting key-value pair. +* Now Java 11 is used to build the library. In particular this results in modern JavaDoc artifact (including the search). + +### 0.6.8 +* [#183] Added: `StreamEx.mapPartial`, `EntryStream.mapToKeyPartial/mapToValuePartial/mapKeyValuePartial` +* [#191] Deprecated: `skipOrdered`. + +### 0.6.7 +* [#76] Added: `StreamEx.zipWith` accepting `BaseStream` (so zipWith(IntStreamEx.ints()) works) +* [#131] Added: `StreamEx.ofCombinations` +* [#164] Added: `Joining.maxElements` +* [#179] Added: `MoreCollectors.onlyOne(Predicate)` + +### 0.6.6 +* [#145] Added: `intersperse` method for all stream types. +* [#144] Added: `EntryStream.generate` +* [#162] Added: `StreamEx.ifEmpty`, `EntryStream.ifEmpty` + +### 0.6.5 +* [#137] Added: `StreamEx.toNavigableMap()`, `EntryStream.toNavigableMap()` +* [#141] Added: `StreamEx.flatArray()`, `EntryStream.flatArray()` +* [#143] Optimized: `AbstractStreamEx.takeWhile/takeWhileInclusive/dropWhile` for parallel unordered case. + +### 0.6.4 +* [#132] Fixed: `StreamEx.parallel(fjp)` does not parallelize underlying Java Stream if it already exists +* [#127] Added: `StreamEx.filterBy` +* [#128] Added: `EntryStream.prefixKeys`, `EntryStream.prefixValues` +* [#135] Added: `StreamEx.removeBy` + +### 0.6.3 + +* [#111] Added: `StreamEx.toArray(elementClass)` +* [#112] Added: `StreamEx.toArray(emptyArray)` +* [#116] Added: `MoreCollectors.ifAllMatch()` +* [#119] Added: `AbstractStreamEx.toImmutableList()`, `AbstractStreamEx.toImmutableSet()`, `EntryStream.toImmutableMap()` +* [#123] Added: `StreamEx.into(collection)`, `EntryStream.into(map)` + +### 0.6.2 + +* [#17] Optimized: `StreamEx.ofTree`, `EntryStream.ofTree`. +* [#104] Added: `StreamEx.ofReversed()`. +* [#105] Added: `MoreCollectors.minMax()`. +* [#108] Added: `IntStreamEx.of(IntBuffer)`, `LongStreamEx.of(LongBuffer)`, `DoubleStreamEx.of(DoubleBuffer)`. + +### 0.6.1 + +* [#90] Changed: `AbstractStreamEx` class (which shares common functionality of `StreamEx` and `EntryStream`) is public now. +* [#92] Added: `IntStreamEx.of(InputStream)`. +* [#93] Added: `IntStreamEx.asByteInputStream()`. +* [#94] Added: `prefix` method for all stream types. + +### 0.6.0 +Warning: this release introduces some changes which may break backwards compatibility. + +* [#67] Changed: `StreamEx.withFirst()` now includes `(first, first)` pair into result as well. If you want to exclude it, use `.withFirst().skip(1)`. +* [#70] Fixed: `MoreCollectors.least()/greatest()` now support null element (if the supplied `Comparator` supports nulls). +* [#70] Fixed: `MoreCollectors.least()/greatest()` now returns stable result (the order of equal elements is not changed). +* [#70] Optimized: `MoreCollectors.least()/greatest()` is usually faster now, especially when the selected elements are close to the stream end. +* [#74] Added: `EntryStream.removeKeyValue()`. +* [#77] Added: `MoreCollectors.filtering()/mapping()/flatMapping()` with default downstream Collector `toList()`. +* [#79] Added: `iterate(seed, predicate, op)` for all stream types. +* [#82] Added: `Emitter` class and primitive friends to create non-trivial stream sources. +* [#83] Changed: `StreamEx.of(Collection)`, `of(Iterator)`, etc. now use `? extends T` type instead of just `T`. +* [#85] Added: `StreamEx.mapFirstOrElse()/mapLastOrElse()`. +* [#86] Added: `peekFirst()`, `peekLast()` for all stream types. +* [#89] Added: `produce()` method for all stream types. +* Updated documentation. + +### 0.5.5 +* [#41] Added: `IntStreamEx/LongStreamEx/StreamEx.without()` accepting several elements. +* [#60] Added: `StreamEx.zipWith()` to zip the stream with another. +* [#63] Optimized `IntStreamEx/LongStreamEx/DoubleStreamEx.reverseSorted()`: much faster now and take less memory. +* [#64] Added: `EntryStream.toMapAndThen()`. +* [#66] Added: `takeWhileInclusive()` for all stream types. +* [#71] Fixed: some collectors like `head(0)`, `greatest(0)` failed when using with JDK Stream. +* [#72] Added: `IntStreamEx.ints()` and `LongStreamEx.longs()`. +* [#73] Added: `EntryStream.collapseKeys()`. + +### 0.5.4 +* [#10] Added: `chain()` method to all stream types allowing fluently chaining custom operations. +* [#55] TailConcatSpliterator implemented; now all `StreamEx/EntryStream.append/prepend` methods are TSO-compatible. +* [#56] Fixed: `StreamEx.append/prepend(Collection)` and `EntryStream.append/prepend(Map)` now properly append/prepend if supplied collection is concurrent (so it may be legally modified during the subsequent operations). +* [#57] JDK Stream creation is deferred until necessary. Now quasi-intermediate operations and especially `headTail()` may work faster. +* [#59] Added: `StreamEx.prepend(value)`, `StreamEx.append(value)` which might work faster than existing var-args methods. +* Updated documentation. + +### 0.5.3 +* [#50] Added: `StreamEx.withFirst()`: extract first stream element +* [#51] Fixed: `StreamEx.parallel(fjp).runLengths()` fails to run the task in the specified pool. +* [#52] `StreamEx.append(T...)` and `prepend(T...)` are declared as @SafeVarargs and final now. +* [#53] Optimized: `mapFirst`/`mapLast` methods will have less overhead now, especially for primitive streams. +* [#54] Added: `StreamEx.headTail()`: map to the new stream using the first stream element and the stream of the rest elements. + +### 0.5.2 +* [#3] Optimized: parallel performance of `StreamEx.ofLines` as well as `StreamEx.split` +* [#19] Optimized: pairMap and forPairs may work faster now, especially in the presence of upstream intermediate operations. +* [#42] Added: `EntryStream.ofTree` methods to stream the tree-like structure tracking nodes depth. +* [#46] Optimized: parallel performance of all `of(Iterator)` methods. +* [#47] Added: `EntryStream.flatMapToKey/flatMapToValue` methods. +* [#48] `EntryStream.of(key, value, key, value...)` now accepts up to 10 pairs. +* Fixed: `StreamEx.of(emptyList().iterator()).parallel()` failed with `NoSuchElementException`. + +### 0.5.1 + +* [#13] Added: `StreamEx.split` to split with single character delimiter. +* [#28] Updated: now `StreamEx.select`, `EntryStream.selectKeys` and `EntryStream.selectValues` accept any type (not necessarily the subtype of current element). +* [#32] Added: `MoreCollectors.dominators` collector which collects the elements to the list leaving only "dominators". +* [#33] Updated: `StreamEx.split("", pattern)` now returns stream of single `""` string instead of empty stream. +* [#35] Added: construction of all stream types from the `Iterator`. +* [#36] Added: `StreamEx.of(Enumeration)` static method. +* [#38] Added: `scanLeft` for primitive streams. +* Updated documentation. + +### 0.5.0 + +Warning: this release introduces some changes which break the backward compatibility and will require the changes in source code if you used the previous StreamEx versions. + +* The package `javax.util.streamex` is renamed to `one.util.streamex`. Every occurrence of `javax.util.streamex` in source files must be replaced with `one.util.streamex`. +* The OSGi Bundle-SymbolicName is changed from `javax.util.streamex` to `one.util.streamex`. +* The Maven groupID is changed from `io.github.amaembo` to `one.util`. Dependencies in pom.xml files should be updated accordingly. +* Added: `StreamEx.ofLines(Path)` and `StreamEx.ofLines(Path, Charset)` +* Added: `MoreCollectors.commonPrefix()/commonSuffix()` short-circuiting collectors. +* Added: `IntStreamEx.of(Integer[])`, `LongStreamEx.of(Long[])`, `DoubleStreamEx.of(Double[])` static methods. +* Deprecated methods `StreamEx.ofEntries()` removed. +* Deprecated methods `collectingAndThen` in primitive collectors removed (use `andThen()` instead). +* Updated documentation. + +### 0.4.1 + +* Added: `StreamEx/IntStreamEx/LongStreamEx/DoubleStreamEx.mapLast/mapFirst` methods. +* Added: `MoreCollectors.flatMapping` collector. +* Added: `Joining` collector: an advanced version of `Collectors.joining` which may short-circuit. +* Fixed: `StreamEx.cross(mapper)` now correctly handles the case when mapper returns null instead of empty stream. +* Optimized: ordered stateful short-circuit collectors now may process less elements in parallel. +* Optimized: `StreamEx/EntryStream.toList()/toListAndThen()/foldRight()/scanRight()` now faster, especially for sized stream. +* Optimized: collapse-based operations like `StreamEx.collapse/groupRuns/runLengths/intervalMap` now may work faster, +especially when stream has more intermediate operations before them. +* Updated documentation. + +### 0.4.0 + +* Introduced the concept of short-circuiting collectors. +* `StreamEx/EntryStream.collect(Collector)` method works as short-circuit operation if short-circuiting collector is passed. +* `MoreCollectors.first/head` collectors are short-circuiting now. +* `MoreCollectors.groupingByEnum` collector may short-circuit if downstream collector is short-circuiting. +* `MoreCollectors.pairing` collector may short-circuit if both downstream collectors are short-circuiting. +* Added new short-circuiting collectors: `onlyOne`, `intersecting`, `toEnumSet`, `andingInt`, `andingLong`. +* Added new collectors: `filtering`, `groupingBy` (with domain specification) which short-circuit when downstream collector is short-circuiting. +* Added collectors `mapping`, `collectingAndThen`, `partitioningBy` which mimic standard JDK collectors, but short-circuit when downstream collector is short-circuiting. +* Added `indexOf` methods for all stream types. +* Added `StreamEx/EntryStream.foldLeft/foldRight` methods without identity argument. +* Added `StreamEx/EntryStream.scanLeft/scanRight` methods without identity argument. +* Added `StreamEx.cartesianProduct/cartesianPower` methods with reduction operator. +* Added `IntStreamEx/LongStreamEx.range/rangeClosed` methods with additional step parameter. +* Added `IntStreamEx/LongStreamEx/DoubleStreamEx.foldLeft` methods. +* Methods `StreamEx/EntryStream.toMap/toSortedMap/toCustomMap` without merge function now produce better exception message in the case of duplicate keys. +* Methods `StreamEx/EntryStream.toMap/toSortedMap/toCustomMap` accepting merge function are not guaranteed to return ConcurrentMap for parallel streams now. They however guarantee now the correct merging order for non-commutative merger functions. +* Methods `StreamEx/EntryStream.grouping*` are not guaranteed to return the ConcurrentMap for parallel streams now. They however guarantee now the correct order of downstream collection. +* Methods `StreamEx.ofEntries` are declared as deprecated and may be removed in future releases! +* Deprecated methods `EntryStream.mapEntryKeys`/`mapEntryValues` are removed! +* Updated documentation + +### 0.3.8 + +* Added `toBooleanArray` collectors (object and primitive). +* Added `MoreCollectors.distinctBy` collector. +* Added `StreamEx/EntryStream.distinct(keyExtractor)` intermediate operation. +* Added `EntryStream.distinctKeys/distinctValues` intermediate operations. +* Added `StreamEx.cartesianPower/cartesianProduct` static methods. +* Optimized: `MoreCollectors.least/greatest` collectors are now much faster (up to 10x depending on input). +* Updated documentation + +### 0.3.7 + +* Added `MoreCollectors.groupingByEnum` collector. +* Added `IntCollector/LongCollector/DoubleCollector.averaging` primitive collectors. +* Added `IntCollector/LongCollector/DoubleCollector.andThen` default methods to replace `collectingAndThen`. +* Added `StreamEx.toFlatCollection` and `StreamEx.toFlatList` terminal operations. +* Added `StreamEx.ofSubLists(list, length, shift)` static method. +* Methods `IntCollector/LongCollector/DoubleCollector.collectingAndThen` are declared as deprecated and may be removed in future releases! +* Updated documentation + +### 0.3.6 + +* Added `StreamEx.collapse(Predicate, Collector)` operation. +* Added `takeWhile` and `dropWhile` methods for all stream types. +* Added `StreamEx.ofPairs` and `EntryStream.ofPairs` methods. +* Optimized: `minBy*/maxBy*` methods for primitive streams now call keyExtractor function at most once per element. +* Updated documentation + +### 0.3.5 + +* Generic arguments relaxed for `StreamEx` methods: `forPairs`, `collapse`, `groupRuns`, `intervalMap`, `sortedBy`. +* Added `MoreCollectors.minIndex/maxIndex` collectors. + +### 0.3.4 + +* Fixed: `EntryStream.of(List)`, `EntryStream.of(T[])` and `StreamEx.runLengths` returned stream +of `Map.Entry` objects which violate the documented contract for `equals` and `hashCode`. +* Fixed: `pairMap` method for all streams worked incorrectly when previous steps included `parallel().flatMap()` due to JDK bug. New version may also work faster in parallel for certain sources. +* Fixed: `collapse`-based methods (`collapse`, `groupRuns`, `runLengths`, `intervalMap`) worked incorrectly in various cases in parallel mode. New version may also work faster in parallel for certain sources. +* Fixed: `minBy*/maxBy*` for primitive streams now return strictly the first matched element (not the arbitrary one). +* Optimized: `minBy/maxBy` methods for primitive streams now call keyExtractor function at most once per element +* Optimized: many stream creation methods (`zip` for all streams, `EntryStream.of(List)`, `StreamEx.ofSubLists`, etc.) now use custom spliterator. +* Optimized: `IntStreamEx.ofChars` reimplemented for JDK 8 as original `CharSequence.chars` implementation is poor. +* Added construction of all stream types from the `Spliterator`. +* Updated documentation + +### 0.3.3 + +* Added `StreamEx.intervalMap` method +* Added `StreamEx.runLengths` method +* Added `StreamEx.ofSubLists` method +* Added `MoreCollectors.countingInt` collector +* `StreamEx/EntryStream.maxBy*/minBy*` methods optimized: now keyExtractor function is called at most once per element +* `StreamEx.groupRuns` method optimized (up to 5x performance boost depending on data) +* `StreamEx.collapse` methods changed: now the elements passed to the predicate are guaranteed to be two adjacent elements from the source stream. +* Updated documentation: now documentation is automatically copied from JDK for the inherited methods. + +### 0.3.2 + +* Added `MoreCollectors` class: several useful collectors absent in JDK +* Added `skipOrdered(n)` method to every Stream implementation +* Updated documentation + +### 0.3.1 + +* Added `mapToEntry` method for primitive streams +* Added `joining` methods family for primitive streams +* Added `StreamEx.collapse`/`groupRuns` methods +* Added `StreamEx.distinct(atLeast)` method +* Released jar works now as an OSGi bundle +* Updated documentation + +### 0.3.0 + +* Added primitive collectors: `IntCollector`, `LongCollector`, `DoubleCollector` +* Added `flatMapToInt`/`flatMapToLong`/`flatMapToDouble`/`flatMapToObj` to primitive streams +* Added `EntryStream.flatMapKeyValue`/`filterKeyValue`/`mapToKey`/`mapToValue` methods +* Added `IntStreamEx.toCharArray`/`toShortArray`/`toByteArray` methods +* Added `DoubleStreamEx.toFloatArray` method +* Generic arguments for many methods are relaxed allowing more flexible usage +* Methods `EntryStream.mapEntryKeys`/`mapEntryValues` are declared as deprecated and may be removed in future releases! +* Updated documentation + +### 0.2.3 + +* Added `toListAndThen()`, `toSetAndThen()` methods to `StreamEx` and `EntryStream` +* Added `StreamEx.cross()` methods family +* Added `EntryStream.peekKeys()`, `EntryStream.peekValues()`, `EntryStream.peekKeyValue()` methods +* Added construction of `EntryStream` from `List` or array (indices are used as keys) +* Added construction of `EntryStream` from two and three key-value pairs +* Added `EntryStream.append`/`prepend` for two and three key-value pairs +* Added `greater`/`less`/`atLeast`/`atMost` filter methods for primitive streams +* Updated documentation + +### 0.2.2 + +* Fixed: `StreamEx.flatMapToEntry`, `EntryStream.flatMapKeys` and `EntryStream.flatMapValues` now correctly handles null value returned by mapper +* Added `StreamEx.scanRight()` and `EntryStream.scanRight()` methods +* Added `StreamEx.foldRight()` and `EntryStream.foldRight()` methods +* Added `StreamEx.forPairs()` method +* Added `StreamEx.partitioningBy()` methods +* Added `StreamEx.partitioningTo()` method +* Added `StreamEx.groupingTo()` methods +* Added `StreamEx.ofPermutations(int)` constructor +* Added `StreamEx.ofTree` constructors +* Added `StreamEx.without()`, `IntStreamEx.without()`, `LongStreamEx.without()` methods +* Added `EntryStream.join()` methods +* Updated documentation + +### 0.2.1 + +* Fixed: `flatCollection` method now correctly handles null value returned by mapper +* Added `IntStreamEx.charsToString`, `IntStreamEx.codePointsToString` methods +* Added `StreamEx.scanLeft()` and `EntryStream.scanLeft()` methods +* Added construction of `EntryStream` by zipping keys and values from two arrays/lists +* Added construction of `StreamEx`/`IntStreamEx`/`LongStreamEx`/`DoubleStreamEx` by zip-mapping two arrays/lists +* Added `pairMap` method for handling adjacent pairs +* The `append`/`prepend` methods of `StreamEx`/`EntryStream` can accept a `Collection` now +* Updated documentation + +### 0.2.0 + +* Added `parallel(fjc)` method for all stream types +* Added `StreamEx.reverseSorted()` method +* Added `StreamEx.foldLeft()` and `EntryStream.foldLeft()` methods +* Added `IntStreramEx.toBitSet()` method +* Added construction of `IntStreamEx` from `char[]`, `short[]`, `byte[]` arrays +* Added construction of `DoubleStreamEx` from `float[]` array +* Updated documentation + +### 0.1.2 + +* Added `IntStreamEx.elements` methods family +* Added construction of the constant stream +* Added `minBy`/`maxBy` methods family for primitive streams +* Updated documentation + +### 0.1.1 + +* Fixed: `empty()` method of all the streams worked incorrectly when used several times +* Added `IntStreamEx.ofIndices` methods family +* Added `IntStreamEx.range(int)` and `LongStreamEx.range(long)` +* Added `StreamEx.ofNullable` +* Added construction of the streams from optionals +* Added construction of the streams from array subrange +* Updated documentation + +### 0.1.0 + +Warning: this release introduces some changes which may break backwards compatibility + +* `EntryStream.toMap(Supplier)` and `EntryStream.toMap(BinaryOperator, Supplier)` renamed to `toCustomMap` +* Added `StreamEx.toSortedMap` and `EntryStream.toSortedMap` methods family +* Methods producing `Map` use concurrent collector for parallel streams if possible +* Updated documentation diff --git a/CHEATSHEET.md b/wiki/CHEATSHEET.md similarity index 97% rename from CHEATSHEET.md rename to wiki/CHEATSHEET.md index d94bccb7..cc031895 100644 --- a/CHEATSHEET.md +++ b/wiki/CHEATSHEET.md @@ -1,290 +1,290 @@ -# StreamEx Cheatsheet - -## Contents - -* [Glossary](#glossary) -* [Stream sources](#stream-sources) -* [New intermediate operations](#new-intermediate-operations) - * [filtering](#filtering) - * [mapping](#mapping) - * [flat-mapping](#flat-mapping) - * [distinct](#distinct) - * [sorting](#sorting) - * [partial reduction](#partial-reduction) - * [concatenate](#concatenate) - * [peek](#peek) - * [misc](#misc-intermediate-operations) -* [New terminal operations](#new-terminal-operations) - * [Collector shortcuts](#collector-shortcuts) - * [Search](#search) - * [Folding](#folding) - * [Primitive operations](#primitive-operations) - * [forEach-like operations](#foreach-like-operations) - * [misc](#misc-terminal-operations) -* [Collectors](#collectors) - * [Basic collectors](#basic-collectors) - * [Adaptor collectors](#adaptor-collectors) - -## Glossary - -* *any*: either of `StreamEx`, `IntStreamEx`, `LongStreamEx`, `DoubleStreamEx`, `EntryStream`, sometimes without `EntryStream`. -* *element*: any object or primitive value which appears in the stream pipeline. -* *entry*: a pair of objects usually (but not always) having the `Map.Entry` semantics. The first object in the pair is *key*, the second one is *value*. - -## Stream sources - -What I want | How to get it ---- | --- -Empty Stream | `any.empty()` -Stream of array, varargs, `Collection`, `Spliterator`, `Iterator`, `Stream` | `any.of()` -Stream of `Enumeration` | `StreamEx.of()` -Stream of array or `List` elements in reverse order | `StreamEx.ofReversed()` -Stream of boxed `Collection`, etc. with unboxing | `IntStreamEx/LongStreamEx/DoubleStreamEx.of()` -Stream of boxed array `Integer[]`, etc. with unboxing | `IntStreamEx/LongStreamEx/DoubleStreamEx.of()` -Stream of `byte[]`, `char[]`, `short[]` array | `IntStreamEx.of()` -Stream of `float[]` array | `DoubleStreamEx.of()` -Infinite Stream from `Supplier` | `any.generate()` -Infinite Stream using iterative function | `any.iterate()` -Convert three-argument for loop to Stream | `any.iterate()` -Fixed length Stream of constant elements | `any.constant()` -Stream from mutable object which is left in the known state after full Stream consumption | `any.produce()` -Custom stream source which maintains mutable state | `Emitter/IntEmitter/LongEmitter/DoubleEmitter` -Stream of array or `List` with indices | `EntryStream.of()` -Stream of single value or empty if null supplied | `StreamEx.ofNullable()` -Stream of `Map` keys (with optional values filter) | `StreamEx.ofKeys()` -Stream of `Map` values (with optional keys filter) | `StreamEx.ofValues()` -Stream of `Map` entries or explicit key-value pairs | `EntryStream.of()` -Zip two arrays or lists | `any.zip()` -Split `CharSequence` with regexp | `StreamEx.split()` -Stream of `List` subLists of fixed length | `StreamEx.ofSubLists()` -Stream of all elements of tree-like structure | `StreamEx.ofTree()` -Stream of all elements of tree-like structure tracking the elements depth | `EntryStream.ofTree()` -Stream of all possible pairs of array or `List` elements | `StreamEx/EntryStream.ofPairs()` -Stream of all possible tuples of given length of `Collection` elements | `StreamEx.cartesianPower()` -Stream of all possible tuples of given `Collection` of collections | `StreamEx.cartesianProduct()` -Stream of permutations | `StreamEx.ofPermutations()` -Stream of combinations | `StreamEx.ofCombinations()` -Stream of array or `List` indices (with optional element filter) | `IntStreamEx.ofIndices()` -Stream of range of integral values (with optional step parameter) | `IntStreamEx/LongStreamEx.range()/rangeClosed()` -Stream of increasing `int` or `long` values | `IntStreamEx.ints()`/`LongStreamEx.longs()` -Stream of random numbers | `IntStreamEx/LongStreamEx/DoubleStreamEx.of(Random, ...)` -Stream of `CharSequence` symbols | `IntStreamEx.ofChars()/ofCodePoints()` -Stream of `BitSet` true bits | `IntStreamEx.of(BitSet)` -Stream of lines from file or `Reader` | `StreamEx.ofLines()` -Stream of bytes from the `InputStream` | `IntStreamEx.of(InputStream)` -Stream of ints from the `IntBuffer` | `IntStreamEx.of(IntBuffer)` -Stream of longs from the `LongBuffer` | `LongStreamEx.of(LongBuffer)` -Stream of doubles from the `DoubleBuffer` | `DoubleStreamEx.of(DoubleBuffer)` - -## New intermediate operations - -### filtering - -What I want | How to get it ---- | --- -Remove nulls | `StreamEx/EntryStream.nonNull()` -Remove entries which keys or values are null | `EntryStream.nonNullKeys()/nonNullValues()` -Remove elements by predicate | `any.remove()` -Remove given elements | `StreamEx/IntStreamEx/LongStreamEx.without()` -Remove by value extracted by supplied mapper function | `StreamEx.removeBy()` -Leave only elements greater/less/at least/at most given value | `IntStreamEx/LongStreamEx/DoubleStreamEx.greater()/atLeast()/less()/atMost()` -Filter by value extracted by supplied mapper function | `StreamEx.filterBy()` -Filter entries which keys or values satisfy the predicate | `EntryStream.filterKeys()/filterValues()` -Filter entries applying the `BiPredicate` to key and value | `EntryStream.filterKeyValue()` -Remove entries which keys or values satisfy the predicate | `EntryStream.removeKeys()/removeValues()` -Remove entries applying the `BiPredicate` to key and value | `EntryStream.removeKeyValue()` -Select elements which are instances of given class | `StreamEx.select()` -Select entries which keys or values are instances of given class | `EntryStream.selectKeys()/selectValues()` -Take stream elements while the condition is true | `any.takeWhile()` -Take stream elements while the condition is true including first violating element | `any.takeWhileInclusive()` -Skip stream elements while the condition is true | `any.dropWhile()` - -### mapping - -What I want | How to get it ---- | --- -Map array or `List` indices to the corresponding elements | `IntStreamEx.elements()` -Map element to the entry | `any.mapToEntry()` -Map entry keys leaving values unchanged | `EntryStream.mapKeys()/mapToKey()` -Map entry values leaving keys unchanged | `EntryStream.mapValues()/mapToValue()` -Map entry key and value using `BiFunction` | `EntryStream.mapKeyValue()` -Swap entry key and value (so entry value becomes key and vice versa) | `EntryStream.invert()` -Drop entry values leaving only keys | `EntryStream.keys()` -Drop entry keys leaving only values | `EntryStream.values()` -Convert every entry to `String` | `EntryStream.join()` -Map pair of adjacent elements to the single element | `any.pairMap()` -Map only first or last element, leaving others as is | `any.mapFirst()/mapLast()` -Map stream element providing special mapper function for the first or last element | `any.mapFirstOrElse()/mapLastOrElse()` -Attach the first stream element to every stream element | `StreamEx.withFirst()` -Map only part of input elements using partial function which returns Optional | `StreamEx.mapPartial()`; `EntryStream.mapToKeyPartial()/mapToValuePartial()/mapKeyValuePartial()` - -### flat-mapping - -What I want | How to get it ---- | --- -Flat-map primitive stream to the stream of other type | `IntStreamEx/LongStreamEx/DoubleStreamEx. flatMapToInt()/flatMapToLong()/flatMapToDouble()/flatMapToObj()` -Flatten multiple collections to the stream of their elements | `StreamEx/EntryStream.flatCollection()` -Flatten multiple arrays to the stream of their elements | `StreamEx/EntryStream.flatArray()` -Flatten multiple maps to the stream of their entries | `StreamEx.flatMapToEntry()` -Perform cross product of current stream with given array, `Collection` or `Stream` source creating entries | `StreamEx.cross()` -Flat-map entry keys leaving values unchanged | `EntryStream.flatMapKeys()/flatMapToKey()` -Flat-map entry values leaving keys unchanged | `EntryStream.flatMapValues()/flatMapToValue()` -Flat-map entry key and value using `BiFunction` | `EntryStream.flatMapKeyValue()` - -### distinct - -What I want | How to get it ---- | --- -Leave only distinct elements which appear at least given number of times | `StreamEx.distinct(atLeast)` -Leave distinct elements using custom key extractor | `StreamEx/EntryStream.distinct(keyExtractor)` -Leave only entries having distinct keys | `EntryStream.distinctKeys()` -Leave only entries having distinct values | `EntryStream.distinctValues()` - -### sorting - -What I want | How to get it ---- | --- -Sort in reverse order | `any.reverseSorted()` -Sort using given key | `any.sortedBy()/sortedByInt()/sortedByLong()/sortedByDouble()` - -### partial reduction - -Partial reduction is a procedure of combining several adjacent stream elements. Usually `BiPredicate` is used to determine which elements should be combined. -`BiPredicate` is applied to the pair of adjacent elements and returns `true` if they should be combined. - -What I want | How to get it ---- | --- -Group some adjacent stream elements into `List` | `StreamEx.groupRuns()` -Reduce some adjacent stream elements using `Collector` or `BinaryOperator` | `StreamEx.collapse()` -Collapse some adjacent stream elements into interval | `StreamEx.intervalMap()` -Remove adjacent duplicate elements counting them | `StreamEx.runLengths()` -Group adjacent entries with equal keys | `EntryStream.collapseKeys()` - -### concatenate - -What I want | How to get it ---- | --- -Add new elements/`Collection`/`Stream` to the end of existing stream | `any.append()` -Add new elements/`Collection`/`Stream` to the beginning of existing stream | `any.prepend()` - -### peek - -What I want | How to get it ---- | --- -Peek only entry keys | `EntryStream.peekKeys()` -Peek only entry values | `EntryStream.peekValues()` -Peek entry keys and values using `BiConsumer` | `EntryStream.peekKeyValue()` -Peek only first or last stream element | `any.peekFirst()/peekLast()` - -### misc intermediate operations - -What I want | How to get it ---- | --- -Extract first stream element and use it to alternate the rest of the stream | `StreamEx.headTail()` -Define almost any custom intermediate operation recursively | `StreamEx.headTail()` -Execute custom-defined operation in fluent manner | `any.chain()` -Perform parallel stream computation using the custom `ForkJoinPool` | `any.parallel(pool)` -Zip two streams together | `StreamEx.zipWith()` -Get the stream of cumulative prefixes | `any.prefix()`/`EntryStream.prefixKeys()`/`EntryStream.prefixValues()` -Intersperse the stream with given delimiters | `any.intersperse()` -Replace the stream contents if the stream is empty | `StreamEx.ifEmpty()`/`EntryStream.ifEmpty()` - -## New terminal operations - -### Collector shortcuts - -What I want | How to get it ---- | --- -Collect elements to `List`, `Set` or custom `Collection` | `StreamEx/EntryStream.toList()/toSet()/toCollection()` -Collect elements to `Collection` adding custom final step | `StreamEx/EntryStream.toListAndThen()/toSetAndThen()/toCollectionAndThen()` -Collect elements to immutable `List` or `Set` | `StreamEx/EntryStream.toImmutableList()/toImmutableSet()` -Collect elements or entries to `Map` | `StreamEx/EntryStream.toMap()/toSortedMap()/toNavigableMap()` -Collect entries to immutable `Map` | `EntryStream.toImmutableMap()` -Collect entries to `Map` adding custom final step | `EntryStream.toMapAndThen()` -Collect entries to custom `Map` | `EntryStream.toCustomMap()` -Partition elements using the `Predicate` | `StreamEx.partitioningBy()/partitioningTo()` -Grouping elements | `StreamEx.groupingBy()/groupingTo()` -Grouping entries | `EntryStream.grouping()/groupingTo()` -Joining elements to `String` | `any.joining()` -Flatten collections and collect them to single final collection | `StreamEx.toFlatList()/toFlatCollection()` -Getting maximal element using custom key extractor | `any.maxBy()/maxByInt()/maxByLong()/maxByDouble()` -Getting minimal element using custom key extractor | `any.minBy()/minByInt()/minByLong()/minByDouble()` - -### Search - -What I want | How to get it ---- | --- -Check whether stream has given element | `StreamEx/EntryStream/IntStreamEx/LongStreamEx.has()` -Find element satisfying the predicate | `any.findFirst(Predicate)/findAny(Predicate)` -Find the index of element satisfying the predicate or equal to given value | `any.indexOf()` - -### Folding - -What I want | How to get it ---- | --- -Fold elements left-to-right | `any.foldLeft()` -Fold elements right-to-left | `StreamEx/EntryStream.foldRight()` -Get `List` of cumulative prefixes or suffixes | `StreamEx/EntryStream.scanLeft()/scanRight()` -Get primitive array of cumulative prefixes | `IntStreamEx/LongStreamEx/DoubleStreamEx.scanLeft()` - -### Primitive operations - -What I want | How to get it ---- | --- -Collect `IntStreamEx` to `byte[]`, `char[]` or `short[]` | `IntStreamEx.toByteArray()/toCharArray()/toShortArray()` -Collect `IntStreamEx` to `BitSet` | `IntStreamEx.toBitSet()` -Collect `DoubleStreamEx` to `float[]` | `DoubleStreamEx.toFloatArray()` -Collect stream of chars or codepoints to `String` | `IntStreamEx.charsToString()/codePointsToString()` - -### forEach-like operations - -What I want | How to get it ---- | --- -Perform operation on every adjacent pair of elements | `StreamEx.forPairs()` -Perform operation on entry key and value using `BiConsumer` | `EntryStream.forKeyValue()` - -### misc terminal operations - -What I want | How to get it ---- | --- -Convert `IntStreamEx` to `InputStream` | `IntStreamEx.asByteInputStream()` -Drain stream content into the existing `Collection` | `StreamEx.into()` -Drain stream content into the existing `Map` | `EntryStream.into()` - -## Collectors - -### Basic collectors - -What I want | How to get it ---- | --- -Collect to array | `MoreCollectors.toArray()` -Collect to boolean array using the `Predicate` applied to each element | `MoreCollectors.toBooleanArray()` -Collect to `EnumSet` | `MoreCollectors.toEnumSet()` -Count number of distinct elements using custom key extractor | `MoreCollectors.distinctCount()` -Get the `List` of distinct elements using custom key extractor | `MoreCollectors.distinctBy()` -Simply counting, but get the result as `Integer` | `MoreCollectors.countingInt()` -Get the first or last element only | `MoreCollectors.first()/last()` -Get the element only if there's exactly one element | `MoreCollectors.onlyOne()` -Get the given number of first or last elements in the `List` | `MoreCollectors.head()/tail()` -Get the given number of greatest/least elements according to the given `Comparator` or natural order | `MoreCollectors.greatest()/least()` -Get all the maximal or minimal elements according to the given `Comparator` or natural order | `MoreCollectors.maxAll()/minAll()` -Get the index of maximal or minimal element according to the given `Comparator` or natural order | `MoreCollectors.minIndex()/maxIndex()` -Get both maximal and minimal stream element according to the given `Comparator` | `MoreCollectors.minMax()` -Get the intersection of input collections | `MoreCollectors.intersecting()` -Get the result bitwise-and operation | `MoreCollectors.andingInt()/andingLong()` -Join the elements into string with possible limit to the string length (adding ellipsis if necessary) | `Joining.with()` -Perform a group-by with the specified keys domain, so every key is initialized even if absent in the input | `MoreCollectors.groupingBy()/groupingByEnum()` -Partition input according to the `Predicate` | `MoreCollectors.partitioningBy()` -Get the common prefix or common suffix `String` of input elements | `MoreCollectors.commonPrefix()/commonSuffix()` -Get the list of input elements removing the elements which follow their dominator element | `MoreCollectors.dominators()` - -### Adaptor collectors - -What I want | How to get it ---- | --- -Collect using two independent collectors | `MoreCollectors.pairing()` -Filter the input before passing to the collector | `MoreCollectors.filtering()` -Map the input before passing to the collector | `MoreCollectors.mapping()` -Flat-map the input before passing to the collector | `MoreCollectors.flatMapping()` -Perform a custom final operation after the collection finishes | `MoreCollectors.collectingAndThen()` +# StreamEx Cheatsheet + +## Contents + +* [Glossary](#glossary) +* [Stream sources](#stream-sources) +* [New intermediate operations](#new-intermediate-operations) + * [filtering](#filtering) + * [mapping](#mapping) + * [flat-mapping](#flat-mapping) + * [distinct](#distinct) + * [sorting](#sorting) + * [partial reduction](#partial-reduction) + * [concatenate](#concatenate) + * [peek](#peek) + * [misc](#misc-intermediate-operations) +* [New terminal operations](#new-terminal-operations) + * [Collector shortcuts](#collector-shortcuts) + * [Search](#search) + * [Folding](#folding) + * [Primitive operations](#primitive-operations) + * [forEach-like operations](#foreach-like-operations) + * [misc](#misc-terminal-operations) +* [Collectors](#collectors) + * [Basic collectors](#basic-collectors) + * [Adaptor collectors](#adaptor-collectors) + +## Glossary + +* *any*: either of `StreamEx`, `IntStreamEx`, `LongStreamEx`, `DoubleStreamEx`, `EntryStream`, sometimes without `EntryStream`. +* *element*: any object or primitive value which appears in the stream pipeline. +* *entry*: a pair of objects usually (but not always) having the `Map.Entry` semantics. The first object in the pair is *key*, the second one is *value*. + +## Stream sources + +What I want | How to get it +--- | --- +Empty Stream | `any.empty()` +Stream of array, varargs, `Collection`, `Spliterator`, `Iterator`, `Stream` | `any.of()` +Stream of `Enumeration` | `StreamEx.of()` +Stream of array or `List` elements in reverse order | `StreamEx.ofReversed()` +Stream of boxed `Collection`, etc. with unboxing | `IntStreamEx/LongStreamEx/DoubleStreamEx.of()` +Stream of boxed array `Integer[]`, etc. with unboxing | `IntStreamEx/LongStreamEx/DoubleStreamEx.of()` +Stream of `byte[]`, `char[]`, `short[]` array | `IntStreamEx.of()` +Stream of `float[]` array | `DoubleStreamEx.of()` +Infinite Stream from `Supplier` | `any.generate()` +Infinite Stream using iterative function | `any.iterate()` +Convert three-argument for loop to Stream | `any.iterate()` +Fixed length Stream of constant elements | `any.constant()` +Stream from mutable object which is left in the known state after full Stream consumption | `any.produce()` +Custom stream source which maintains mutable state | `Emitter/IntEmitter/LongEmitter/DoubleEmitter` +Stream of array or `List` with indices | `EntryStream.of()` +Stream of single value or empty if null supplied | `StreamEx.ofNullable()` +Stream of `Map` keys (with optional values filter) | `StreamEx.ofKeys()` +Stream of `Map` values (with optional keys filter) | `StreamEx.ofValues()` +Stream of `Map` entries or explicit key-value pairs | `EntryStream.of()` +Zip two arrays or lists | `any.zip()` +Split `CharSequence` with regexp | `StreamEx.split()` +Stream of `List` subLists of fixed length | `StreamEx.ofSubLists()` +Stream of all elements of tree-like structure | `StreamEx.ofTree()` +Stream of all elements of tree-like structure tracking the elements depth | `EntryStream.ofTree()` +Stream of all possible pairs of array or `List` elements | `StreamEx/EntryStream.ofPairs()` +Stream of all possible tuples of given length of `Collection` elements | `StreamEx.cartesianPower()` +Stream of all possible tuples of given `Collection` of collections | `StreamEx.cartesianProduct()` +Stream of permutations | `StreamEx.ofPermutations()` +Stream of combinations | `StreamEx.ofCombinations()` +Stream of array or `List` indices (with optional element filter) | `IntStreamEx.ofIndices()` +Stream of range of integral values (with optional step parameter) | `IntStreamEx/LongStreamEx.range()/rangeClosed()` +Stream of increasing `int` or `long` values | `IntStreamEx.ints()`/`LongStreamEx.longs()` +Stream of random numbers | `IntStreamEx/LongStreamEx/DoubleStreamEx.of(Random, ...)` +Stream of `CharSequence` symbols | `IntStreamEx.ofChars()/ofCodePoints()` +Stream of `BitSet` true bits | `IntStreamEx.of(BitSet)` +Stream of lines from file or `Reader` | `StreamEx.ofLines()` +Stream of bytes from the `InputStream` | `IntStreamEx.of(InputStream)` +Stream of ints from the `IntBuffer` | `IntStreamEx.of(IntBuffer)` +Stream of longs from the `LongBuffer` | `LongStreamEx.of(LongBuffer)` +Stream of doubles from the `DoubleBuffer` | `DoubleStreamEx.of(DoubleBuffer)` + +## New intermediate operations + +### filtering + +What I want | How to get it +--- | --- +Remove nulls | `StreamEx/EntryStream.nonNull()` +Remove entries which keys or values are null | `EntryStream.nonNullKeys()/nonNullValues()` +Remove elements by predicate | `any.remove()` +Remove given elements | `StreamEx/IntStreamEx/LongStreamEx.without()` +Remove by value extracted by supplied mapper function | `StreamEx.removeBy()` +Leave only elements greater/less/at least/at most given value | `IntStreamEx/LongStreamEx/DoubleStreamEx.greater()/atLeast()/less()/atMost()` +Filter by value extracted by supplied mapper function | `StreamEx.filterBy()` +Filter entries which keys or values satisfy the predicate | `EntryStream.filterKeys()/filterValues()` +Filter entries applying the `BiPredicate` to key and value | `EntryStream.filterKeyValue()` +Remove entries which keys or values satisfy the predicate | `EntryStream.removeKeys()/removeValues()` +Remove entries applying the `BiPredicate` to key and value | `EntryStream.removeKeyValue()` +Select elements which are instances of given class | `StreamEx.select()` +Select entries which keys or values are instances of given class | `EntryStream.selectKeys()/selectValues()` +Take stream elements while the condition is true | `any.takeWhile()` +Take stream elements while the condition is true including first violating element | `any.takeWhileInclusive()` +Skip stream elements while the condition is true | `any.dropWhile()` + +### mapping + +What I want | How to get it +--- | --- +Map array or `List` indices to the corresponding elements | `IntStreamEx.elements()` +Map element to the entry | `any.mapToEntry()` +Map entry keys leaving values unchanged | `EntryStream.mapKeys()/mapToKey()` +Map entry values leaving keys unchanged | `EntryStream.mapValues()/mapToValue()` +Map entry key and value using `BiFunction` | `EntryStream.mapKeyValue()` +Swap entry key and value (so entry value becomes key and vice versa) | `EntryStream.invert()` +Drop entry values leaving only keys | `EntryStream.keys()` +Drop entry keys leaving only values | `EntryStream.values()` +Convert every entry to `String` | `EntryStream.join()` +Map pair of adjacent elements to the single element | `any.pairMap()` +Map only first or last element, leaving others as is | `any.mapFirst()/mapLast()` +Map stream element providing special mapper function for the first or last element | `any.mapFirstOrElse()/mapLastOrElse()` +Attach the first stream element to every stream element | `StreamEx.withFirst()` +Map only part of input elements using partial function which returns Optional | `StreamEx.mapPartial()`; `EntryStream.mapToKeyPartial()/mapToValuePartial()/mapKeyValuePartial()` + +### flat-mapping + +What I want | How to get it +--- | --- +Flat-map primitive stream to the stream of other type | `IntStreamEx/LongStreamEx/DoubleStreamEx. flatMapToInt()/flatMapToLong()/flatMapToDouble()/flatMapToObj()` +Flatten multiple collections to the stream of their elements | `StreamEx/EntryStream.flatCollection()` +Flatten multiple arrays to the stream of their elements | `StreamEx/EntryStream.flatArray()` +Flatten multiple maps to the stream of their entries | `StreamEx.flatMapToEntry()` +Perform cross product of current stream with given array, `Collection` or `Stream` source creating entries | `StreamEx.cross()` +Flat-map entry keys leaving values unchanged | `EntryStream.flatMapKeys()/flatMapToKey()` +Flat-map entry values leaving keys unchanged | `EntryStream.flatMapValues()/flatMapToValue()` +Flat-map entry key and value using `BiFunction` | `EntryStream.flatMapKeyValue()` + +### distinct + +What I want | How to get it +--- | --- +Leave only distinct elements which appear at least given number of times | `StreamEx.distinct(atLeast)` +Leave distinct elements using custom key extractor | `StreamEx/EntryStream.distinct(keyExtractor)` +Leave only entries having distinct keys | `EntryStream.distinctKeys()` +Leave only entries having distinct values | `EntryStream.distinctValues()` + +### sorting + +What I want | How to get it +--- | --- +Sort in reverse order | `any.reverseSorted()` +Sort using given key | `any.sortedBy()/sortedByInt()/sortedByLong()/sortedByDouble()` + +### partial reduction + +Partial reduction is a procedure of combining several adjacent stream elements. Usually `BiPredicate` is used to determine which elements should be combined. +`BiPredicate` is applied to the pair of adjacent elements and returns `true` if they should be combined. + +What I want | How to get it +--- | --- +Group some adjacent stream elements into `List` | `StreamEx.groupRuns()` +Reduce some adjacent stream elements using `Collector` or `BinaryOperator` | `StreamEx.collapse()` +Collapse some adjacent stream elements into interval | `StreamEx.intervalMap()` +Remove adjacent duplicate elements counting them | `StreamEx.runLengths()` +Group adjacent entries with equal keys | `EntryStream.collapseKeys()` + +### concatenate + +What I want | How to get it +--- | --- +Add new elements/`Collection`/`Stream` to the end of existing stream | `any.append()` +Add new elements/`Collection`/`Stream` to the beginning of existing stream | `any.prepend()` + +### peek + +What I want | How to get it +--- | --- +Peek only entry keys | `EntryStream.peekKeys()` +Peek only entry values | `EntryStream.peekValues()` +Peek entry keys and values using `BiConsumer` | `EntryStream.peekKeyValue()` +Peek only first or last stream element | `any.peekFirst()/peekLast()` + +### misc intermediate operations + +What I want | How to get it +--- | --- +Extract first stream element and use it to alternate the rest of the stream | `StreamEx.headTail()` +Define almost any custom intermediate operation recursively | `StreamEx.headTail()` +Execute custom-defined operation in fluent manner | `any.chain()` +Perform parallel stream computation using the custom `ForkJoinPool` | `any.parallel(pool)` +Zip two streams together | `StreamEx.zipWith()` +Get the stream of cumulative prefixes | `any.prefix()`/`EntryStream.prefixKeys()`/`EntryStream.prefixValues()` +Intersperse the stream with given delimiters | `any.intersperse()` +Replace the stream contents if the stream is empty | `StreamEx.ifEmpty()`/`EntryStream.ifEmpty()` + +## New terminal operations + +### Collector shortcuts + +What I want | How to get it +--- | --- +Collect elements to `List`, `Set` or custom `Collection` | `StreamEx/EntryStream.toList()/toSet()/toCollection()` +Collect elements to `Collection` adding custom final step | `StreamEx/EntryStream.toListAndThen()/toSetAndThen()/toCollectionAndThen()` +Collect elements to immutable `List` or `Set` | `StreamEx/EntryStream.toImmutableList()/toImmutableSet()` +Collect elements or entries to `Map` | `StreamEx/EntryStream.toMap()/toSortedMap()/toNavigableMap()` +Collect entries to immutable `Map` | `EntryStream.toImmutableMap()` +Collect entries to `Map` adding custom final step | `EntryStream.toMapAndThen()` +Collect entries to custom `Map` | `EntryStream.toCustomMap()` +Partition elements using the `Predicate` | `StreamEx.partitioningBy()/partitioningTo()` +Grouping elements | `StreamEx.groupingBy()/groupingTo()` +Grouping entries | `EntryStream.grouping()/groupingTo()` +Joining elements to `String` | `any.joining()` +Flatten collections and collect them to single final collection | `StreamEx.toFlatList()/toFlatCollection()` +Getting maximal element using custom key extractor | `any.maxBy()/maxByInt()/maxByLong()/maxByDouble()` +Getting minimal element using custom key extractor | `any.minBy()/minByInt()/minByLong()/minByDouble()` + +### Search + +What I want | How to get it +--- | --- +Check whether stream has given element | `StreamEx/EntryStream/IntStreamEx/LongStreamEx.has()` +Find element satisfying the predicate | `any.findFirst(Predicate)/findAny(Predicate)` +Find the index of element satisfying the predicate or equal to given value | `any.indexOf()` + +### Folding + +What I want | How to get it +--- | --- +Fold elements left-to-right | `any.foldLeft()` +Fold elements right-to-left | `StreamEx/EntryStream.foldRight()` +Get `List` of cumulative prefixes or suffixes | `StreamEx/EntryStream.scanLeft()/scanRight()` +Get primitive array of cumulative prefixes | `IntStreamEx/LongStreamEx/DoubleStreamEx.scanLeft()` + +### Primitive operations + +What I want | How to get it +--- | --- +Collect `IntStreamEx` to `byte[]`, `char[]` or `short[]` | `IntStreamEx.toByteArray()/toCharArray()/toShortArray()` +Collect `IntStreamEx` to `BitSet` | `IntStreamEx.toBitSet()` +Collect `DoubleStreamEx` to `float[]` | `DoubleStreamEx.toFloatArray()` +Collect stream of chars or codepoints to `String` | `IntStreamEx.charsToString()/codePointsToString()` + +### forEach-like operations + +What I want | How to get it +--- | --- +Perform operation on every adjacent pair of elements | `StreamEx.forPairs()` +Perform operation on entry key and value using `BiConsumer` | `EntryStream.forKeyValue()` + +### misc terminal operations + +What I want | How to get it +--- | --- +Convert `IntStreamEx` to `InputStream` | `IntStreamEx.asByteInputStream()` +Drain stream content into the existing `Collection` | `StreamEx.into()` +Drain stream content into the existing `Map` | `EntryStream.into()` + +## Collectors + +### Basic collectors + +What I want | How to get it +--- | --- +Collect to array | `MoreCollectors.toArray()` +Collect to boolean array using the `Predicate` applied to each element | `MoreCollectors.toBooleanArray()` +Collect to `EnumSet` | `MoreCollectors.toEnumSet()` +Count number of distinct elements using custom key extractor | `MoreCollectors.distinctCount()` +Get the `List` of distinct elements using custom key extractor | `MoreCollectors.distinctBy()` +Simply counting, but get the result as `Integer` | `MoreCollectors.countingInt()` +Get the first or last element only | `MoreCollectors.first()/last()` +Get the element only if there's exactly one element | `MoreCollectors.onlyOne()` +Get the given number of first or last elements in the `List` | `MoreCollectors.head()/tail()` +Get the given number of greatest/least elements according to the given `Comparator` or natural order | `MoreCollectors.greatest()/least()` +Get all the maximal or minimal elements according to the given `Comparator` or natural order | `MoreCollectors.maxAll()/minAll()` +Get the index of maximal or minimal element according to the given `Comparator` or natural order | `MoreCollectors.minIndex()/maxIndex()` +Get both maximal and minimal stream element according to the given `Comparator` | `MoreCollectors.minMax()` +Get the intersection of input collections | `MoreCollectors.intersecting()` +Get the result bitwise-and operation | `MoreCollectors.andingInt()/andingLong()` +Join the elements into string with possible limit to the string length (adding ellipsis if necessary) | `Joining.with()` +Perform a group-by with the specified keys domain, so every key is initialized even if absent in the input | `MoreCollectors.groupingBy()/groupingByEnum()` +Partition input according to the `Predicate` | `MoreCollectors.partitioningBy()` +Get the common prefix or common suffix `String` of input elements | `MoreCollectors.commonPrefix()/commonSuffix()` +Get the list of input elements removing the elements which follow their dominator element | `MoreCollectors.dominators()` + +### Adaptor collectors + +What I want | How to get it +--- | --- +Collect using two independent collectors | `MoreCollectors.pairing()` +Filter the input before passing to the collector | `MoreCollectors.filtering()` +Map the input before passing to the collector | `MoreCollectors.mapping()` +Flat-map the input before passing to the collector | `MoreCollectors.flatMapping()` +Perform a custom final operation after the collection finishes | `MoreCollectors.collectingAndThen()` Perform a downstream collection if all elements satisfy the predicate | `MoreCollectors.ifAllMatch()` \ No newline at end of file diff --git a/MIGRATION.md b/wiki/MIGRATION.md similarity index 98% rename from MIGRATION.md rename to wiki/MIGRATION.md index 2da03e58..1e7a1f5f 100644 --- a/MIGRATION.md +++ b/wiki/MIGRATION.md @@ -1,31 +1,31 @@ -# Migration between StreamEx releases - -This document describes StreamEx changes which may break the backwards compatibility. For full list of changes see [CHANGES.md](CHANGES.md). - -### 0.7.0 -Issue#194: Method `skipOrdered` is removed, which may break source and binary compatibility if in was used. Use simply `skip` instead. -PR#200: Overloads added to `EntryStream.allMatch/anyMatch/noneMatch` which accept a `BiPredicate`. Such overloads may cause - source incompatibility in rare case when a method reference was used which is either bound to var-arg method or - has several overloads. E.g. assuming `boolean allNull(Object... objects)` now `EntryStream.of(...).allMatch(Utils::allNull)` - won't compile anymore. To work-around this issue use a lambda instead of method reference. - -### 0.6.0 - -Issue#67: Now `StreamEx.withFirst()` as well as `StreamEx.withFirst(BinaryOperator)` include `(first, first)` pair. If you used these operations in StreamEx 0.5.3-0.5.5, you should update the existing code: replace `.withFirst()` with `.withFirst().skip(1)`. - -### 0.5.5 - -Issue#41: As `StreamEx.without(T...)` was added, the existing code may become ambiguous now. If you've used `.without(null)` before, replace it with dedicated `.nonNull()` operation. - -Issue#63: `DoubleStreamEx.reverseSorted()` may change the order of non-canonical `NaN` values (actually sorting them). - -### 0.5.3 - -Issue#52: `StreamEx.append(T...)` and `prepend(T...)` are final now, so if you extend `StreamEx` class, you cannot override them anymore. - -### 0.5.0 - -Issue#8: The package `javax.util.streamex` is renamed to `one.util.streamex`. The OSGi bundle name and Maven groupId are changed correspondingly. To migrate to StreamEx 0.5.0 you should: - -* Replace every occurrence of `javax.util.streamex` to `one.util.streamex` in your Java files and OSGi manifests. -* Replace `io.github.amaembo` groupID with `one.util` in your build files (pom.xml, ivy.xml, build.gradle, etc.) +# Migration between StreamEx releases + +This document describes StreamEx changes which may break the backwards compatibility. For full list of changes see [CHANGES.md](CHANGES.md). + +### 0.7.0 +Issue#194: Method `skipOrdered` is removed, which may break source and binary compatibility if in was used. Use simply `skip` instead. +PR#200: Overloads added to `EntryStream.allMatch/anyMatch/noneMatch` which accept a `BiPredicate`. Such overloads may cause + source incompatibility in rare case when a method reference was used which is either bound to var-arg method or + has several overloads. E.g. assuming `boolean allNull(Object... objects)` now `EntryStream.of(...).allMatch(Utils::allNull)` + won't compile anymore. To work-around this issue use a lambda instead of method reference. + +### 0.6.0 + +Issue#67: Now `StreamEx.withFirst()` as well as `StreamEx.withFirst(BinaryOperator)` include `(first, first)` pair. If you used these operations in StreamEx 0.5.3-0.5.5, you should update the existing code: replace `.withFirst()` with `.withFirst().skip(1)`. + +### 0.5.5 + +Issue#41: As `StreamEx.without(T...)` was added, the existing code may become ambiguous now. If you've used `.without(null)` before, replace it with dedicated `.nonNull()` operation. + +Issue#63: `DoubleStreamEx.reverseSorted()` may change the order of non-canonical `NaN` values (actually sorting them). + +### 0.5.3 + +Issue#52: `StreamEx.append(T...)` and `prepend(T...)` are final now, so if you extend `StreamEx` class, you cannot override them anymore. + +### 0.5.0 + +Issue#8: The package `javax.util.streamex` is renamed to `one.util.streamex`. The OSGi bundle name and Maven groupId are changed correspondingly. To migrate to StreamEx 0.5.0 you should: + +* Replace every occurrence of `javax.util.streamex` to `one.util.streamex` in your Java files and OSGi manifests. +* Replace `io.github.amaembo` groupID with `one.util` in your build files (pom.xml, ivy.xml, build.gradle, etc.)