diff --git a/.idea/libraries/Maven__junit_junit_4_12.xml b/.idea/libraries/Maven__junit_junit_4_12.xml
deleted file mode 100644
index d4110417..00000000
--- a/.idea/libraries/Maven__junit_junit_4_12.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/libraries/Maven__junit_junit_4_13.xml b/.idea/libraries/Maven__junit_junit_4_13.xml
new file mode 100644
index 00000000..6d570690
--- /dev/null
+++ b/.idea/libraries/Maven__junit_junit_4_13.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/streamex.iml b/.idea/streamex.iml
index 4e3316bc..ce83ddbd 100644
--- a/.idea/streamex.iml
+++ b/.idea/streamex.iml
@@ -10,7 +10,7 @@
-
+
-
\ No newline at end of file
+
diff --git a/pom.xml b/pom.xml
index 77759294..da478d8c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -55,7 +55,7 @@
junit
junit
- 4.12
+ 4.13
test
diff --git a/src/test/java/one/util/streamex/AverageLongTest.java b/src/test/java/one/util/streamex/AverageLongTest.java
index 6516ba4a..2a11cfe3 100644
--- a/src/test/java/one/util/streamex/AverageLongTest.java
+++ b/src/test/java/one/util/streamex/AverageLongTest.java
@@ -1,109 +1,109 @@
-/*
- * Copyright 2015, 2019 StreamEx contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package one.util.streamex;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.math.MathContext;
-import java.util.Arrays;
-import java.util.OptionalDouble;
-import java.util.function.BiFunction;
-import java.util.function.Supplier;
-import java.util.stream.Collector;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-import java.util.stream.LongStream;
-
-import org.junit.Test;
-
-import static one.util.streamex.Internals.AverageLong;
-import static one.util.streamex.TestHelpers.repeat;
-import static one.util.streamex.TestHelpers.withRandom;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-
-/**
- * @author Tagir Valeev
- */
-public class AverageLongTest {
-
- @Test
- public void testAverageLongNoOverflow() {
- AverageLong avg = new AverageLong();
- assertFalse(avg.result().isPresent());
- avg.accept(1);
- avg.accept(2);
- avg.accept(3);
- assertEquals(2.0, avg.result().getAsDouble(), 0.0);
-
- avg.accept(2);
- avg.accept(-4);
- avg.accept(8);
- assertEquals(2.0, avg.result().getAsDouble(), 0.0);
-
- AverageLong avg1 = new AverageLong();
- avg1.accept(-2);
- AverageLong avg2 = new AverageLong();
- avg2.accept(-2);
- assertEquals(-2.0, avg1.combine(avg2).result().getAsDouble(), 0.0);
-
- withRandom(r -> {
- int[] input = r.ints(1000).toArray();
- OptionalDouble expected = IntStream.of(input).average();
- assertEquals(expected, Arrays.stream(input)
- .collect(AverageLong::new, AverageLong::accept, AverageLong::combine).result());
-
- assertEquals(expected, Arrays.stream(input).parallel().collect(AverageLong::new, AverageLong::accept,
- AverageLong::combine).result());
- });
- }
-
- @Test
- public void testCombine() {
- withRandom(r -> repeat(100, i -> {
- AverageLong avg1 = new AverageLong();
- AverageLong avg2 = new AverageLong();
- long[] set1 = r.longs(100).toArray();
- long[] set2 = r.longs(100).toArray();
- double expected = LongStreamEx.of(set1).append(set2).boxed().collect(getBigIntegerAverager()).getAsDouble();
- LongStream.of(set1).forEach(avg1::accept);
- LongStream.of(set2).forEach(avg2::accept);
- assertEquals(expected, avg1.combine(avg2).result().getAsDouble(), Math.abs(expected / 1e14));
- }));
- }
-
- @Test
- public void testCompareToBigInteger() {
- withRandom(r -> {
- long[] input = LongStreamEx.of(r, 1000).toArray();
- Supplier supplier = () -> Arrays.stream(input);
- double expected = supplier.get().boxed().collect(getBigIntegerAverager()).getAsDouble();
- assertEquals(expected, supplier.get().collect(AverageLong::new, AverageLong::accept, AverageLong::combine)
- .result().getAsDouble(), Math.abs(expected) / 1e14);
- assertEquals(expected, supplier.get().parallel().collect(AverageLong::new, AverageLong::accept,
- AverageLong::combine).result().getAsDouble(), Math.abs(expected) / 1e14);
- });
- }
-
- private static Collector getBigIntegerAverager() {
- BiFunction finisher = (BigInteger sum, Long cnt) -> cnt == 0L ? OptionalDouble
- .empty()
- : OptionalDouble.of(new BigDecimal(sum).divide(BigDecimal.valueOf(cnt), MathContext.DECIMAL64)
- .doubleValue());
- return MoreCollectors.pairing(Collectors.reducing(BigInteger.ZERO,
- BigInteger::valueOf, BigInteger::add), Collectors.counting(), finisher);
- }
-}
+/*
+ * Copyright 2015, 2019 StreamEx contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package one.util.streamex;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.math.MathContext;
+import java.util.Arrays;
+import java.util.OptionalDouble;
+import java.util.function.BiFunction;
+import java.util.function.Supplier;
+import java.util.stream.Collector;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+
+import org.junit.Test;
+
+import static one.util.streamex.Internals.AverageLong;
+import static one.util.streamex.TestHelpers.repeat;
+import static one.util.streamex.TestHelpers.withRandom;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+
+/**
+ * @author Tagir Valeev
+ */
+public class AverageLongTest {
+
+ @Test
+ public void testAverageLongNoOverflow() {
+ AverageLong avg = new AverageLong();
+ assertFalse(avg.result().isPresent());
+ avg.accept(1);
+ avg.accept(2);
+ avg.accept(3);
+ assertEquals(2.0, avg.result().getAsDouble(), 0.0);
+
+ avg.accept(2);
+ avg.accept(-4);
+ avg.accept(8);
+ assertEquals(2.0, avg.result().getAsDouble(), 0.0);
+
+ AverageLong avg1 = new AverageLong();
+ avg1.accept(-2);
+ AverageLong avg2 = new AverageLong();
+ avg2.accept(-2);
+ assertEquals(-2.0, avg1.combine(avg2).result().getAsDouble(), 0.0);
+
+ withRandom(r -> {
+ int[] input = r.ints(1000).toArray();
+ OptionalDouble expected = IntStream.of(input).average();
+ assertEquals(expected, Arrays.stream(input)
+ .collect(AverageLong::new, AverageLong::accept, AverageLong::combine).result());
+
+ assertEquals(expected, Arrays.stream(input).parallel().collect(AverageLong::new, AverageLong::accept,
+ AverageLong::combine).result());
+ });
+ }
+
+ @Test
+ public void testCombine() {
+ withRandom(r -> repeat(100, i -> {
+ AverageLong avg1 = new AverageLong();
+ AverageLong avg2 = new AverageLong();
+ long[] set1 = r.longs(100).toArray();
+ long[] set2 = r.longs(100).toArray();
+ double expected = LongStreamEx.of(set1).append(set2).boxed().collect(getBigIntegerAverager()).getAsDouble();
+ LongStream.of(set1).forEach(avg1::accept);
+ LongStream.of(set2).forEach(avg2::accept);
+ assertEquals(expected, avg1.combine(avg2).result().getAsDouble(), Math.abs(expected / 1e14));
+ }));
+ }
+
+ @Test
+ public void testCompareToBigInteger() {
+ withRandom(r -> {
+ long[] input = LongStreamEx.of(r, 1000).toArray();
+ Supplier supplier = () -> Arrays.stream(input);
+ double expected = supplier.get().boxed().collect(getBigIntegerAverager()).getAsDouble();
+ assertEquals(expected, supplier.get().collect(AverageLong::new, AverageLong::accept, AverageLong::combine)
+ .result().getAsDouble(), Math.abs(expected) / 1e14);
+ assertEquals(expected, supplier.get().parallel().collect(AverageLong::new, AverageLong::accept,
+ AverageLong::combine).result().getAsDouble(), Math.abs(expected) / 1e14);
+ });
+ }
+
+ private static Collector getBigIntegerAverager() {
+ BiFunction finisher = (BigInteger sum, Long cnt) -> cnt == 0L ? OptionalDouble
+ .empty()
+ : OptionalDouble.of(new BigDecimal(sum).divide(BigDecimal.valueOf(cnt), MathContext.DECIMAL64)
+ .doubleValue());
+ return MoreCollectors.pairing(Collectors.reducing(BigInteger.ZERO,
+ BigInteger::valueOf, BigInteger::add), Collectors.counting(), finisher);
+ }
+}
diff --git a/src/test/java/one/util/streamex/EntryStreamInternalTest.java b/src/test/java/one/util/streamex/EntryStreamInternalTest.java
new file mode 100644
index 00000000..2477de1f
--- /dev/null
+++ b/src/test/java/one/util/streamex/EntryStreamInternalTest.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2015, 2020 StreamEx contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package one.util.streamex;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runners.MethodSorters;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+
+/**
+ * @author Tagir Valeev
+ */
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class EntryStreamInternalTest {
+
+ @Test
+ public void testCreate() {
+ EntryStream stream = EntryStream.of(createMap());
+ assertSame(stream.stream(), EntryStream.of(stream).stream());
+ assertSame(stream.stream(), EntryStream.of(StreamEx.of(EntryStream.of(stream))).stream());
+ }
+
+ private static Map createMap() {
+ Map data = new LinkedHashMap<>();
+ data.put("a", 1);
+ data.put("bb", 22);
+ data.put("ccc", 33);
+ return data;
+ }
+
+}
diff --git a/src/test/java/one/util/streamex/StreamExInternalTest.java b/src/test/java/one/util/streamex/StreamExInternalTest.java
new file mode 100644
index 00000000..4e34905b
--- /dev/null
+++ b/src/test/java/one/util/streamex/StreamExInternalTest.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2015, 2020 StreamEx contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package one.util.streamex;
+
+import java.util.Spliterator;
+
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runners.MethodSorters;
+
+import static java.util.Arrays.asList;
+import static one.util.streamex.TestHelpers.streamEx;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+
+/**
+ * @author Tagir Valeev
+ */
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class StreamExInternalTest {
+ @Test
+ public void testCreate() {
+ StreamEx stream = StreamEx.of("foo", "bar");
+ assertSame(stream.stream(), StreamEx.of(stream).stream());
+ }
+
+ @Test
+ public void testDropWhile() {
+ // Test that in JDK9 operation is propagated to JDK dropWhile method.
+ boolean hasDropWhile = VerSpec.VER_SPEC.getClass().getSimpleName().equals("Java9Specific");
+ Spliterator spliterator = StreamEx.of("aaa", "b", "cccc").dropWhile(x -> x.length() > 1).spliterator();
+ assertEquals(hasDropWhile, !spliterator.getClass().getSimpleName().equals("TDOfRef"));
+ }
+
+ @Test
+ public void testSplit() {
+ assertEquals(CharSpliterator.class, StreamEx.split("a#a", "\\#").spliterator().getClass());
+ }
+}
diff --git a/src/test/java/one/util/streamex/TestHelpers.java b/src/test/java/one/util/streamex/TestHelpers.java
index 3e95a906..e3cf7313 100644
--- a/src/test/java/one/util/streamex/TestHelpers.java
+++ b/src/test/java/one/util/streamex/TestHelpers.java
@@ -1,504 +1,519 @@
-/*
- * Copyright 2015, 2019 StreamEx contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package one.util.streamex;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Objects;
-import java.util.Random;
-import java.util.Set;
-import java.util.Spliterator;
-import java.util.Spliterators;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ThreadLocalRandom;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.function.Consumer;
-import java.util.function.Function;
-import java.util.function.IntConsumer;
-import java.util.function.Predicate;
-import java.util.function.Supplier;
-import java.util.stream.Collector;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-import java.util.stream.LongStream;
-import java.util.stream.Stream;
-
-import org.junit.ComparisonFailure;
-
-import static one.util.streamex.Internals.TailSpliterator;
-import static one.util.streamex.Internals.finished;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-/**
- * @author Tagir Valeev
- */
-public class TestHelpers {
-
- enum Mode {
- NORMAL, SPLITERATOR, PARALLEL, APPEND, PREPEND, RANDOM
- }
-
- static class StreamSupplier {
- final Mode mode;
- final Supplier> base;
-
- public StreamSupplier(Supplier> base, Mode mode) {
- this.base = base;
- this.mode = mode;
- }
-
- public Stream get() {
- Stream res = base.get();
- switch (mode) {
- case NORMAL:
- case SPLITERATOR:
- return res.sequential();
- case PARALLEL:
- return res.parallel();
- case APPEND:
- // using Stream.empty() or Arrays.asList() here is optimized out
- // in append/prepend which is undesired
- return StreamEx.of(res.parallel()).append(new ConcurrentLinkedQueue<>());
- case PREPEND:
- return StreamEx.of(res.parallel()).prepend(new ConcurrentLinkedQueue<>());
- case RANDOM:
- return StreamEx.of(new EmptyingSpliterator<>(res.parallel().spliterator())).parallel();
- default:
- throw new InternalError("Unsupported mode: " + mode);
- }
- }
-
- @Override
- public String toString() {
- return mode.toString();
- }
- }
-
- static class StreamExSupplier extends StreamSupplier {
-
- public StreamExSupplier(Supplier> base, Mode mode) {
- super(base, mode);
- }
-
- @Override
- public StreamEx get() {
- if (mode == Mode.SPLITERATOR)
- return StreamEx.of(base.get().spliterator());
- return StreamEx.of(super.get());
- }
- }
-
- static class EntryStreamSupplier extends StreamSupplier> {
-
- public EntryStreamSupplier(Supplier>> base, Mode mode) {
- super(base, mode);
- }
-
- @Override
- public EntryStream get() {
- return EntryStream.of(super.get());
- }
- }
-
- static List> streamEx(Supplier> base) {
- return StreamEx.of(Mode.values()).map(mode -> new StreamExSupplier<>(base, mode)).toList();
- }
-
- /**
- * Run the consumer once feeding it with RNG initialized with auto-generated seed
- * adding the seed value to every failed assertion message
- *
- * @param cons consumer to run
- */
- static void withRandom(Consumer cons) {
- long seed = ThreadLocalRandom.current().nextLong();
- withRandom(seed, cons);
- }
-
- /**
- * Run the consumer once feeding it with RNG initialized with given seed
- * adding the seed value to every failed assertion message
- *
- * @param seed random seed to use
- * @param cons consumer to run
- */
- static void withRandom(long seed, Consumer cons) {
- Random random = new Random(seed);
- withMessage("Using new Random(" + seed + ")", () -> cons.accept(random));
- }
-
- /**
- * Run the runnable automatically adding given message to every failed assertion
- *
- * @param message message to prepend
- * @param r runnable to run
- */
- private static void withMessage(String message, Runnable r) {
- try {
- r.run();
- } catch (ComparisonFailure cmp) {
- ComparisonFailure ex = new ComparisonFailure(message + ": " + cmp.getMessage(), cmp.getExpected(), cmp
- .getActual());
- ex.setStackTrace(cmp.getStackTrace());
- throw ex;
- } catch (AssertionError err) {
- AssertionError ex = new AssertionError(message + ": " + err.getMessage(), err.getCause());
- ex.setStackTrace(err.getStackTrace());
- throw ex;
- } catch (RuntimeException | Error err) {
- throw new RuntimeException(message + ": " + err.getMessage(), err);
- }
- }
-
- static void repeat(int times, IntConsumer consumer) {
- for (int i = 1; i <= times; i++) {
- int finalI = i;
- withMessage("#" + i, () -> consumer.accept(finalI));
- }
- }
-
- static void streamEx(Supplier> base, Consumer> consumer) {
- for (StreamExSupplier supplier : StreamEx.of(Mode.values()).map(mode -> new StreamExSupplier<>(base, mode))) {
- withMessage(supplier.toString(), () -> consumer.accept(supplier));
- }
- }
-
- static void intStreamEx(Supplier base, Consumer consumer) {
- streamEx(() -> base.get().boxed(), s -> consumer.accept(s.get().mapToInt(x -> x)));
- }
-
- static void longStreamEx(Supplier base, Consumer consumer) {
- streamEx(() -> base.get().boxed(), s -> consumer.accept(s.get().mapToLong(x -> x)));
- }
-
- static void emptyStreamEx(Class clazz, Consumer> consumer) {
- streamEx(Stream::empty, consumer);
- }
-
- static void entryStream(Supplier>> base, Consumer> consumer) {
- for (EntryStreamSupplier supplier : StreamEx.of(Mode.values()).map(
- mode -> new EntryStreamSupplier<>(base, mode))) {
- withMessage(supplier.toString(), () -> consumer.accept(supplier));
- }
- }
-
- /**
- * Spliterator which randomly inserts empty spliterators on splitting
- *
- * @author Tagir Valeev
- *
- * @param type of the elements
- */
- private static class EmptyingSpliterator implements Spliterator {
- private Spliterator source;
-
- public EmptyingSpliterator(Spliterator source) {
- this.source = Objects.requireNonNull(source);
- }
-
- @Override
- public boolean tryAdvance(Consumer super T> action) {
- return source.tryAdvance(action);
- }
-
- @Override
- public void forEachRemaining(Consumer super T> action) {
- source.forEachRemaining(action);
- }
-
- @Override
- public Comparator super T> getComparator() {
- return source.getComparator();
- }
-
- @Override
- public Spliterator trySplit() {
- Spliterator source = this.source;
- switch (ThreadLocalRandom.current().nextInt(3)) {
- case 0:
- return Spliterators.emptySpliterator();
- case 1:
- this.source = Spliterators.emptySpliterator();
- return source;
- default:
- Spliterator split = source.trySplit();
- return split == null ? null : new EmptyingSpliterator<>(split);
- }
- }
-
- @Override
- public long estimateSize() {
- return source.estimateSize();
- }
-
- @Override
- public int characteristics() {
- return source.characteristics();
- }
- }
-
- static void checkCollectorEmpty(String message, R expected, Collector collector) {
- if (finished(collector) != null)
- checkShortCircuitCollector(message, expected, 0, Stream::empty, collector);
- else
- checkCollector(message, expected, Stream::empty, collector);
- }
-
- static void checkShortCircuitCollector(String message, R expected,
- int expectedConsumedElements, Supplier> base, Collector collector) {
- checkShortCircuitCollector(message, expected, expectedConsumedElements, base, collector, false);
- }
-
- static void checkShortCircuitCollector(String message, R expected,
- int expectedConsumedElements, Supplier> base, Collector collector, boolean skipIdentity) {
- assertNotNull(message, finished(collector));
- Collector withIdentity = Collectors.collectingAndThen(collector, Function.identity());
- for (StreamExSupplier supplier : streamEx(base)) {
- AtomicInteger counter = new AtomicInteger();
- assertEquals(message + ": " + supplier, expected, supplier.get().peek(t -> counter.incrementAndGet())
- .collect(collector));
- if (!supplier.get().isParallel())
- assertEquals(message + ": " + supplier + ": consumed: ", expectedConsumedElements, counter.get());
- if (!skipIdentity)
- assertEquals(message + ": " + supplier, expected, supplier.get().collect(withIdentity));
- }
- }
-
- static void checkCollector(String message, R expected, Supplier> base,
- Collector collector) {
- // use checkShortCircuitCollector for CancellableCollector
- assertNull(message, finished(collector));
- for (StreamExSupplier supplier : streamEx(base)) {
- assertEquals(message + ": " + supplier, expected, supplier.get().collect(collector));
- }
- }
-
- static void checkSpliterator(String msg, Supplier> supplier) {
- List expected = new ArrayList<>();
- supplier.get().forEachRemaining(expected::add);
- checkSpliterator(msg, expected, supplier);
- }
-
- /*
- * Tests whether spliterators produced by given supplier produce the
- * expected result under various splittings
- *
- * This test is single-threaded. Its behavior is randomized, but random seed
- * will be printed in case of failure, so the results could be reproduced
- */
- static void checkSpliterator(String msg, List expected, Supplier> supplier) {
- List seq = new ArrayList<>();
-
- // Test characteristics
- Spliterator forCharacteristics = supplier.get();
- if (forCharacteristics.hasCharacteristics(Spliterator.SORTED)) {
- forCharacteristics.getComparator(); // must not fail
- }
- assertTrue(forCharacteristics.estimateSize() >= 0);
-
- // Test forEachRemaining
- Spliterator sequential = supplier.get();
- sequential.forEachRemaining(seq::add);
- assertFalse(msg, sequential.tryAdvance(t -> fail(msg + ": Advance called with " + t)));
- sequential.forEachRemaining(t -> fail(msg + ": Advance called with " + t));
- assertEquals(msg, expected, seq);
-
- // Test tryAdvance
- seq.clear();
- sequential = supplier.get();
- while (true) {
- AtomicBoolean called = new AtomicBoolean();
- boolean res = sequential.tryAdvance(t -> {
- seq.add(t);
- called.set(true);
- });
- if (res != called.get()) {
- fail(msg
- + (res ? ": Consumer not called, but spliterator returned true"
- : ": Consumer called, but spliterator returned false"));
- }
- if (!res)
- break;
- }
- assertFalse(msg, sequential.tryAdvance(t -> fail(msg + ": Advance called with " + t)));
- assertEquals(msg, expected, seq);
-
- // Test TailSpliterator
- if (sequential instanceof TailSpliterator) {
- seq.clear();
- TailSpliterator.forEachWithTail(supplier.get(), seq::add);
- assertEquals(msg, expected, seq);
- seq.clear();
- sequential = supplier.get();
- while (sequential != null) {
- sequential = TailSpliterator.tryAdvanceWithTail(sequential, seq::add);
- }
- }
- assertEquals(msg, expected, seq);
-
- // Test advance+remaining
- for (int i = 1; i < Math.min(4, expected.size() - 1); i++) {
- seq.clear();
- sequential = supplier.get();
- for (int j = 0; j < i; j++) assertTrue(msg, sequential.tryAdvance(seq::add));
- sequential.forEachRemaining(seq::add);
- assertEquals(msg, expected, seq);
- }
-
- // Test trySplit
- withRandom(r -> {
- repeat(500, n -> {
- Spliterator spliterator = supplier.get();
- List> spliterators = new ArrayList<>();
- spliterators.add(spliterator);
- int p = r.nextInt(10) + 2;
- for (int i = 0; i < p; i++) {
- int idx = r.nextInt(spliterators.size());
- Spliterator split = spliterators.get(idx).trySplit();
- if (split != null)
- spliterators.add(idx, split);
- }
- List order = IntStreamEx.ofIndices(spliterators).boxed().toList();
- Collections.shuffle(order, r);
- List list = StreamEx.of(order).mapToEntry(idx -> {
- Spliterator s = spliterators.get(idx);
- Stream.Builder builder = Stream.builder();
- s.forEachRemaining(builder);
- assertFalse(msg, s.tryAdvance(t -> fail(msg + ": Advance called with " + t)));
- s.forEachRemaining(t -> fail(msg + ": Advance called with " + t));
- return builder.build();
- }).sortedBy(Entry::getKey).values().flatMap(Function.identity()).toList();
- assertEquals(msg, expected, list);
- });
- repeat(500, n -> {
- Spliterator spliterator = supplier.get();
- List> spliterators = new ArrayList<>();
- spliterators.add(spliterator);
- int p = r.nextInt(30) + 2;
- for (int i = 0; i < p; i++) {
- int idx = r.nextInt(spliterators.size());
- Spliterator split = spliterators.get(idx).trySplit();
- if (split != null)
- spliterators.add(idx, split);
- }
- List> results = StreamEx.>generate(ArrayList::new).limit(spliterators.size())
- .toList();
- int count = spliterators.size();
- while (count > 0) {
- int i;
- do {
- i = r.nextInt(spliterators.size());
- spliterator = spliterators.get(i);
- } while (spliterator == null);
- if (!spliterator.tryAdvance(results.get(i)::add)) {
- spliterators.set(i, null);
- count--;
- }
- }
- List list = StreamEx.of(results).flatMap(List::stream).toList();
- assertEquals(msg, expected, list);
- });
- });
- }
-
- static void consumeElement(Spliterator spliterator, T element) {
- boolean[] consumed = {false};
- assertTrue(spliterator.tryAdvance(x -> {
- assertEquals(element, x);
- consumed[0] = true;
- }));
- assertTrue(consumed[0]);
- }
-
- static void consumeElement(Spliterator spliterator, Set remainingElements) {
- boolean[] consumed = {false};
- assertTrue(spliterator.tryAdvance(x -> {
- assertTrue(remainingElements.remove(x));
- consumed[0] = true;
- }));
- assertTrue(consumed[0]);
- }
-
- static void checkIllegalStateException(Runnable r, String key, String value1, String value2) {
- try {
- r.run();
- fail("no exception");
- } catch (IllegalStateException ex) {
- String exmsg = ex.getMessage();
- if (!exmsg.equals("Duplicate entry for key '" + key + "' (attempt to merge values '" + value1 + "' and '"
- + value2 + "')")
- && !exmsg.equals("Duplicate entry for key '" + key + "' (attempt to merge values '" + value2
- + "' and '" + value1 + "')")
- && !exmsg.equals("java.lang.IllegalStateException: Duplicate entry for key '" + key
- + "' (attempt to merge values '" + value1 + "' and '" + value2 + "')")
- && !exmsg.equals("java.lang.IllegalStateException: Duplicate entry for key '" + key
- + "' (attempt to merge values '" + value2 + "' and '" + value1 + "')"))
- fail("wrong exception message: " + exmsg);
- }
- }
-
- @FunctionalInterface
- interface Statement {
- void evaluate() throws Throwable;
- }
-
- static void assertThrows(Class extends Throwable> expected, Statement statement) {
- assertThrows(expected, msg -> true, statement);
- }
-
- static void assertThrows(Class extends Throwable> expected, Predicate super String> checkExceptionAction,
- Statement statement) {
- try {
- statement.evaluate();
- } catch (Throwable e) {
- if (!expected.isAssignableFrom(e.getClass())) {
- throw new AssertionError("Unexpected exception, " +
- "expected<" + expected.getName() + "> " +
- "but was<" + e.getClass().getName() + ">", e);
- }
- if (!checkExceptionAction.test(e.getMessage())) {
- fail("Unexpected exception<" + e.getMessage() + ">");
- }
- return;
- }
- fail("Expected exception: " + expected.getName());
- }
-
- static Spliterator emptySpliteratorWithExactSize(long exactSize) {
- return new Spliterators.AbstractSpliterator(0, Spliterator.SIZED) {
-
- @Override
- public long getExactSizeIfKnown() {
- return exactSize;
- }
-
- @Override
- public boolean tryAdvance(Consumer super T> ignored) {
- return false;
- }
- };
- }
-}
+/*
+ * Copyright 2015, 2020 StreamEx contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package one.util.streamex;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Objects;
+import java.util.Random;
+import java.util.Set;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.IntConsumer;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
+import java.util.stream.Collector;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+import java.util.stream.Stream;
+
+import org.junit.ComparisonFailure;
+
+import static one.util.streamex.Internals.TailSpliterator;
+import static one.util.streamex.Internals.finished;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+/**
+ * @author Tagir Valeev
+ */
+public class TestHelpers {
+
+ enum Mode {
+ NORMAL, SPLITERATOR, PARALLEL, APPEND, PREPEND, RANDOM
+ }
+
+ static class StreamSupplier {
+ final Mode mode;
+ final Supplier> base;
+
+ public StreamSupplier(Supplier> base, Mode mode) {
+ this.base = base;
+ this.mode = mode;
+ }
+
+ public Stream get() {
+ Stream res = base.get();
+ switch (mode) {
+ case NORMAL:
+ case SPLITERATOR:
+ return res.sequential();
+ case PARALLEL:
+ return res.parallel();
+ case APPEND:
+ // using Stream.empty() or Arrays.asList() here is optimized out
+ // in append/prepend which is undesired
+ return StreamEx.of(res.parallel()).append(new ConcurrentLinkedQueue<>());
+ case PREPEND:
+ return StreamEx.of(res.parallel()).prepend(new ConcurrentLinkedQueue<>());
+ case RANDOM:
+ return StreamEx.of(new EmptyingSpliterator<>(res.parallel().spliterator())).parallel();
+ default:
+ throw new InternalError("Unsupported mode: " + mode);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return mode.toString();
+ }
+ }
+
+ public static class StreamExSupplier extends StreamSupplier {
+
+ public StreamExSupplier(Supplier> base, Mode mode) {
+ super(base, mode);
+ }
+
+ @Override
+ public StreamEx get() {
+ if (mode == Mode.SPLITERATOR)
+ return StreamEx.of(base.get().spliterator());
+ return StreamEx.of(super.get());
+ }
+ }
+
+ public static class EntryStreamSupplier extends StreamSupplier> {
+
+ public EntryStreamSupplier(Supplier>> base, Mode mode) {
+ super(base, mode);
+ }
+
+ @Override
+ public EntryStream get() {
+ return EntryStream.of(super.get());
+ }
+ }
+
+ public static class Point {
+ public final double x, y;
+
+ public Point(double x, double y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ public double distance(Point o) {
+ return Math.sqrt((x - o.x) * (x - o.x) + (y - o.y) * (y - o.y));
+ }
+ }
+
+ public static List> streamEx(Supplier> base) {
+ return StreamEx.of(Mode.values()).map(mode -> new StreamExSupplier<>(base, mode)).toList();
+ }
+
+ /**
+ * Run the consumer once feeding it with RNG initialized with auto-generated seed
+ * adding the seed value to every failed assertion message
+ *
+ * @param cons consumer to run
+ */
+ public static void withRandom(Consumer cons) {
+ long seed = ThreadLocalRandom.current().nextLong();
+ withRandom(seed, cons);
+ }
+
+ /**
+ * Run the consumer once feeding it with RNG initialized with given seed
+ * adding the seed value to every failed assertion message
+ *
+ * @param seed random seed to use
+ * @param cons consumer to run
+ */
+ public static void withRandom(long seed, Consumer cons) {
+ Random random = new Random(seed);
+ withMessage("Using new Random(" + seed + ")", () -> cons.accept(random));
+ }
+
+ /**
+ * Run the runnable automatically adding given message to every failed assertion
+ *
+ * @param message message to prepend
+ * @param r runnable to run
+ */
+ private static void withMessage(String message, Runnable r) {
+ try {
+ r.run();
+ } catch (ComparisonFailure cmp) {
+ ComparisonFailure ex = new ComparisonFailure(message + ": " + cmp.getMessage(), cmp.getExpected(), cmp
+ .getActual());
+ ex.setStackTrace(cmp.getStackTrace());
+ throw ex;
+ } catch (AssertionError err) {
+ AssertionError ex = new AssertionError(message + ": " + err.getMessage(), err.getCause());
+ ex.setStackTrace(err.getStackTrace());
+ throw ex;
+ } catch (RuntimeException | Error err) {
+ throw new RuntimeException(message + ": " + err.getMessage(), err);
+ }
+ }
+
+ public static void repeat(int times, IntConsumer consumer) {
+ for (int i = 1; i <= times; i++) {
+ int finalI = i;
+ withMessage("#" + i, () -> consumer.accept(finalI));
+ }
+ }
+
+ public static void streamEx(Supplier> base, Consumer> consumer) {
+ for (StreamExSupplier supplier : StreamEx.of(Mode.values()).map(mode -> new StreamExSupplier<>(base, mode))) {
+ withMessage(supplier.toString(), () -> consumer.accept(supplier));
+ }
+ }
+
+ public static void intStreamEx(Supplier base, Consumer consumer) {
+ streamEx(() -> base.get().boxed(), s -> consumer.accept(s.get().mapToInt(x -> x)));
+ }
+
+ public static void longStreamEx(Supplier base, Consumer consumer) {
+ streamEx(() -> base.get().boxed(), s -> consumer.accept(s.get().mapToLong(x -> x)));
+ }
+
+ public static void emptyStreamEx(Class clazz, Consumer> consumer) {
+ streamEx(Stream::empty, consumer);
+ }
+
+ public static void entryStream(Supplier>> base,
+ Consumer> consumer) {
+ for (EntryStreamSupplier supplier : StreamEx.of(Mode.values()).map(
+ mode -> new EntryStreamSupplier<>(base, mode))) {
+ withMessage(supplier.toString(), () -> consumer.accept(supplier));
+ }
+ }
+
+ /**
+ * Spliterator which randomly inserts empty spliterators on splitting
+ *
+ * @author Tagir Valeev
+ *
+ * @param type of the elements
+ */
+ private static class EmptyingSpliterator implements Spliterator {
+ private Spliterator source;
+
+ public EmptyingSpliterator(Spliterator source) {
+ this.source = Objects.requireNonNull(source);
+ }
+
+ @Override
+ public boolean tryAdvance(Consumer super T> action) {
+ return source.tryAdvance(action);
+ }
+
+ @Override
+ public void forEachRemaining(Consumer super T> action) {
+ source.forEachRemaining(action);
+ }
+
+ @Override
+ public Comparator super T> getComparator() {
+ return source.getComparator();
+ }
+
+ @Override
+ public Spliterator trySplit() {
+ Spliterator source = this.source;
+ switch (ThreadLocalRandom.current().nextInt(3)) {
+ case 0:
+ return Spliterators.emptySpliterator();
+ case 1:
+ this.source = Spliterators.emptySpliterator();
+ return source;
+ default:
+ Spliterator split = source.trySplit();
+ return split == null ? null : new EmptyingSpliterator<>(split);
+ }
+ }
+
+ @Override
+ public long estimateSize() {
+ return source.estimateSize();
+ }
+
+ @Override
+ public int characteristics() {
+ return source.characteristics();
+ }
+ }
+
+ public static void checkCollectorEmpty(String message, R expected, Collector collector) {
+ if (finished(collector) != null)
+ checkShortCircuitCollector(message, expected, 0, Stream::empty, collector);
+ else
+ checkCollector(message, expected, Stream::empty, collector);
+ }
+
+ public static void checkShortCircuitCollector(String message, R expected,
+ int expectedConsumedElements, Supplier> base, Collector collector) {
+ checkShortCircuitCollector(message, expected, expectedConsumedElements, base, collector, false);
+ }
+
+ public static void checkShortCircuitCollector(String message, R expected,
+ int expectedConsumedElements, Supplier> base, Collector collector, boolean skipIdentity) {
+ assertNotNull(message, finished(collector));
+ Collector withIdentity = Collectors.collectingAndThen(collector, Function.identity());
+ for (StreamExSupplier supplier : streamEx(base)) {
+ AtomicInteger counter = new AtomicInteger();
+ assertEquals(message + ": " + supplier, expected, supplier.get().peek(t -> counter.incrementAndGet())
+ .collect(collector));
+ if (!supplier.get().isParallel())
+ assertEquals(message + ": " + supplier + ": consumed: ", expectedConsumedElements, counter.get());
+ if (!skipIdentity)
+ assertEquals(message + ": " + supplier, expected, supplier.get().collect(withIdentity));
+ }
+ }
+
+ public static void checkCollector(String message, R expected, Supplier> base,
+ Collector collector) {
+ // use checkShortCircuitCollector for CancellableCollector
+ assertNull(message, finished(collector));
+ for (StreamExSupplier supplier : streamEx(base)) {
+ assertEquals(message + ": " + supplier, expected, supplier.get().collect(collector));
+ }
+ }
+
+ public static void checkSpliterator(String msg, Supplier> supplier) {
+ List expected = new ArrayList<>();
+ supplier.get().forEachRemaining(expected::add);
+ checkSpliterator(msg, expected, supplier);
+ }
+
+ /*
+ * Tests whether spliterators produced by given supplier produce the
+ * expected result under various splittings
+ *
+ * This test is single-threaded. Its behavior is randomized, but random seed
+ * will be printed in case of failure, so the results could be reproduced
+ */
+ public static void checkSpliterator(String msg, List expected, Supplier> supplier) {
+ List seq = new ArrayList<>();
+
+ // Test characteristics
+ Spliterator forCharacteristics = supplier.get();
+ if (forCharacteristics.hasCharacteristics(Spliterator.SORTED)) {
+ forCharacteristics.getComparator(); // must not fail
+ }
+ assertTrue(forCharacteristics.estimateSize() >= 0);
+
+ // Test forEachRemaining
+ Spliterator sequential = supplier.get();
+ sequential.forEachRemaining(seq::add);
+ assertFalse(msg, sequential.tryAdvance(t -> fail(msg + ": Advance called with " + t)));
+ sequential.forEachRemaining(t -> fail(msg + ": Advance called with " + t));
+ assertEquals(msg, expected, seq);
+
+ // Test tryAdvance
+ seq.clear();
+ sequential = supplier.get();
+ while (true) {
+ AtomicBoolean called = new AtomicBoolean();
+ boolean res = sequential.tryAdvance(t -> {
+ seq.add(t);
+ called.set(true);
+ });
+ if (res != called.get()) {
+ fail(msg
+ + (res ? ": Consumer not called, but spliterator returned true"
+ : ": Consumer called, but spliterator returned false"));
+ }
+ if (!res)
+ break;
+ }
+ assertFalse(msg, sequential.tryAdvance(t -> fail(msg + ": Advance called with " + t)));
+ assertEquals(msg, expected, seq);
+
+ // Test TailSpliterator
+ if (sequential instanceof TailSpliterator) {
+ seq.clear();
+ TailSpliterator.forEachWithTail(supplier.get(), seq::add);
+ assertEquals(msg, expected, seq);
+ seq.clear();
+ sequential = supplier.get();
+ while (sequential != null) {
+ sequential = TailSpliterator.tryAdvanceWithTail(sequential, seq::add);
+ }
+ }
+ assertEquals(msg, expected, seq);
+
+ // Test advance+remaining
+ for (int i = 1; i < Math.min(4, expected.size() - 1); i++) {
+ seq.clear();
+ sequential = supplier.get();
+ for (int j = 0; j < i; j++) assertTrue(msg, sequential.tryAdvance(seq::add));
+ sequential.forEachRemaining(seq::add);
+ assertEquals(msg, expected, seq);
+ }
+
+ // Test trySplit
+ withRandom(r -> {
+ repeat(500, n -> {
+ Spliterator spliterator = supplier.get();
+ List> spliterators = new ArrayList<>();
+ spliterators.add(spliterator);
+ int p = r.nextInt(10) + 2;
+ for (int i = 0; i < p; i++) {
+ int idx = r.nextInt(spliterators.size());
+ Spliterator split = spliterators.get(idx).trySplit();
+ if (split != null)
+ spliterators.add(idx, split);
+ }
+ List order = IntStreamEx.ofIndices(spliterators).boxed().toList();
+ Collections.shuffle(order, r);
+ List list = StreamEx.of(order).mapToEntry(idx -> {
+ Spliterator s = spliterators.get(idx);
+ Stream.Builder builder = Stream.builder();
+ s.forEachRemaining(builder);
+ assertFalse(msg, s.tryAdvance(t -> fail(msg + ": Advance called with " + t)));
+ s.forEachRemaining(t -> fail(msg + ": Advance called with " + t));
+ return builder.build();
+ }).sortedBy(Entry::getKey).values().flatMap(Function.identity()).toList();
+ assertEquals(msg, expected, list);
+ });
+ repeat(500, n -> {
+ Spliterator spliterator = supplier.get();
+ List> spliterators = new ArrayList<>();
+ spliterators.add(spliterator);
+ int p = r.nextInt(30) + 2;
+ for (int i = 0; i < p; i++) {
+ int idx = r.nextInt(spliterators.size());
+ Spliterator split = spliterators.get(idx).trySplit();
+ if (split != null)
+ spliterators.add(idx, split);
+ }
+ List> results = StreamEx.>generate(ArrayList::new).limit(spliterators.size())
+ .toList();
+ int count = spliterators.size();
+ while (count > 0) {
+ int i;
+ do {
+ i = r.nextInt(spliterators.size());
+ spliterator = spliterators.get(i);
+ } while (spliterator == null);
+ if (!spliterator.tryAdvance(results.get(i)::add)) {
+ spliterators.set(i, null);
+ count--;
+ }
+ }
+ List list = StreamEx.of(results).flatMap(List::stream).toList();
+ assertEquals(msg, expected, list);
+ });
+ });
+ }
+
+ public static void consumeElement(Spliterator spliterator, T element) {
+ boolean[] consumed = {false};
+ assertTrue(spliterator.tryAdvance(x -> {
+ assertEquals(element, x);
+ consumed[0] = true;
+ }));
+ assertTrue(consumed[0]);
+ }
+
+ public static void consumeElement(Spliterator spliterator, Set remainingElements) {
+ boolean[] consumed = {false};
+ assertTrue(spliterator.tryAdvance(x -> {
+ assertTrue(remainingElements.remove(x));
+ consumed[0] = true;
+ }));
+ assertTrue(consumed[0]);
+ }
+
+ public static void checkIllegalStateException(Runnable r, String key, String value1, String value2) {
+ try {
+ r.run();
+ fail("no exception");
+ } catch (IllegalStateException ex) {
+ String exmsg = ex.getMessage();
+ if (!exmsg.equals("Duplicate entry for key '" + key + "' (attempt to merge values '" + value1 + "' and '"
+ + value2 + "')")
+ && !exmsg.equals("Duplicate entry for key '" + key + "' (attempt to merge values '" + value2
+ + "' and '" + value1 + "')")
+ && !exmsg.equals("java.lang.IllegalStateException: Duplicate entry for key '" + key
+ + "' (attempt to merge values '" + value1 + "' and '" + value2 + "')")
+ && !exmsg.equals("java.lang.IllegalStateException: Duplicate entry for key '" + key
+ + "' (attempt to merge values '" + value2 + "' and '" + value1 + "')"))
+ fail("wrong exception message: " + exmsg);
+ }
+ }
+
+ @FunctionalInterface
+ public interface Statement {
+ void evaluate() throws Throwable;
+ }
+
+ public static void assertStatementThrows(Class extends Throwable> expected,
+ Predicate super String> checkExceptionAction,
+ Statement statement) {
+ try {
+ statement.evaluate();
+ } catch (Throwable e) {
+ if (!expected.isAssignableFrom(e.getClass())) {
+ throw new AssertionError("Unexpected exception, " +
+ "expected<" + expected.getName() + "> " +
+ "but was<" + e.getClass().getName() + ">", e);
+ }
+ if (!checkExceptionAction.test(e.getMessage())) {
+ fail("Unexpected exception<" + e.getMessage() + ">");
+ }
+ return;
+ }
+ fail("Expected exception: " + expected.getName());
+ }
+
+ public static Spliterator emptySpliteratorWithExactSize(long exactSize) {
+ return new Spliterators.AbstractSpliterator(0, Spliterator.SIZED) {
+
+ @Override
+ public long getExactSizeIfKnown() {
+ return exactSize;
+ }
+
+ @Override
+ public boolean tryAdvance(Consumer super T> ignored) {
+ return false;
+ }
+ };
+ }
+
+ public static void checkAsString(String expected, EntryStream, ?> stream) {
+ assertEquals(expected, stream.join("->").joining(";"));
+ }
+}
diff --git a/src/test/java/one/util/streamex/BaseStreamExTest.java b/src/test/java/one/util/streamex/api/BaseStreamExTest.java
similarity index 90%
rename from src/test/java/one/util/streamex/BaseStreamExTest.java
rename to src/test/java/one/util/streamex/api/BaseStreamExTest.java
index 1d9c9450..c0cfd455 100644
--- a/src/test/java/one/util/streamex/BaseStreamExTest.java
+++ b/src/test/java/one/util/streamex/api/BaseStreamExTest.java
@@ -1,124 +1,130 @@
-/*
- * Copyright 2015, 2019 StreamEx contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package one.util.streamex;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Spliterator;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.function.Function;
-import java.util.stream.Stream;
-
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-/**
- * @author Tagir Valeev
- */
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class BaseStreamExTest {
- @Test
- public void testSpliterator() {
- Spliterator spltr = Arrays.spliterator(new Integer[]{1, 2, 3});
- StreamEx s = StreamEx.of(spltr);
- assertFalse(s.isParallel());
- assertSame(spltr, s.spliterator());
- }
-
- @Test(expected = IllegalStateException.class)
- public void testSpliteratorConsumed() {
- StreamEx s = StreamEx.of(1, 2, 3);
- assertNotNull(s.spliterator());
- s.spliterator();
- }
-
- @Test(expected = IllegalStateException.class)
- public void testStreamConsumed() {
- StreamEx s = StreamEx.of(1, 2, 3);
- assertNotNull(s.spliterator());
- s.count();
- }
-
- @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)
- .onClose(() -> closeHandlers.add("After map"))
- .pairMap(Integer::sum)
- .onClose(() -> closeHandlers.add("After pairMap"))
- .append(4)
- .onClose(() -> closeHandlers.add("After append"))
- .prepend(Stream.of(5).onClose(() -> closeHandlers.add("Prepended Stream")))
- .prepend(StreamEx.of(6).onClose(() -> closeHandlers.add("Prepended StreamEx")));
- assertEquals(Arrays.asList(6, 5, 6, 10, 4), stream.toList());
- assertTrue(closeHandlers.isEmpty());
- stream.close();
- assertEquals(Arrays.asList("Orig stream", "StreamEx", "After map", "After pairMap", "After append",
- "Prepended Stream", "Prepended StreamEx"), closeHandlers);
- closeHandlers.clear();
- stream.close();
- assertTrue(closeHandlers.isEmpty());
- }
-
- @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")))
- .onClose(ex.apply("StreamEx"))
- .map(x -> x * 2)
- .onClose(() -> flag.set(true))
- .pairMap(Integer::sum)
- .onClose(ex.apply("After pairMap"))
- .append(4)
- .onClose(ex.apply("After append"))
- .prepend(Stream.of(5).onClose(ex.apply("Prepended Stream")))
- .prepend(StreamEx.of(6).onClose(ex.apply("Prepended StreamEx")));
- assertEquals(Arrays.asList(6, 5, 6, 10, 4), stream.toList());
- try {
- stream.close();
- } 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(
- Throwable::getMessage).toList());
- assertTrue(flag.get());
- return;
- }
- fail("No exception");
- }
-
- @Test
- public void testChain() {
- assertArrayEquals(new double[] { 2, 2, 6, 2, 6 }, IntStreamEx.of(3, 4, 5).chain(IntStreamEx::boxed).chain(
- s -> s.flatMapToLong(LongStreamEx::range)).chain(s -> s.filter(n -> n % 2 != 0).asDoubleStream()).chain(
- s -> s.map(x -> x * 2)).toArray(), 0.0);
- }
-}
+/*
+ * Copyright 2015, 2019 StreamEx contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package one.util.streamex.api;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Spliterator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runners.MethodSorters;
+
+import one.util.streamex.IntStreamEx;
+import one.util.streamex.LongStreamEx;
+import one.util.streamex.StreamEx;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+/**
+ * @author Tagir Valeev
+ */
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class BaseStreamExTest {
+ @Test
+ public void testSpliterator() {
+ Spliterator spltr = Arrays.spliterator(new Integer[]{1, 2, 3});
+ StreamEx s = StreamEx.of(spltr);
+ assertFalse(s.isParallel());
+ assertSame(spltr, s.spliterator());
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void testSpliteratorConsumed() {
+ StreamEx s = StreamEx.of(1, 2, 3);
+ assertNotNull(s.spliterator());
+ s.spliterator();
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void testStreamConsumed() {
+ StreamEx s = StreamEx.of(1, 2, 3);
+ assertNotNull(s.spliterator());
+ s.count();
+ }
+
+ @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)
+ .onClose(() -> closeHandlers.add("After map"))
+ .pairMap(Integer::sum)
+ .onClose(() -> closeHandlers.add("After pairMap"))
+ .append(4)
+ .onClose(() -> closeHandlers.add("After append"))
+ .prepend(Stream.of(5).onClose(() -> closeHandlers.add("Prepended Stream")))
+ .prepend(StreamEx.of(6).onClose(() -> closeHandlers.add("Prepended StreamEx")));
+ assertEquals(Arrays.asList(6, 5, 6, 10, 4), stream.toList());
+ assertTrue(closeHandlers.isEmpty());
+ stream.close();
+ assertEquals(Arrays.asList("Orig stream", "StreamEx", "After map", "After pairMap", "After append",
+ "Prepended Stream", "Prepended StreamEx"), closeHandlers);
+ closeHandlers.clear();
+ stream.close();
+ assertTrue(closeHandlers.isEmpty());
+ }
+
+ @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")))
+ .onClose(ex.apply("StreamEx"))
+ .map(x -> x * 2)
+ .onClose(() -> flag.set(true))
+ .pairMap(Integer::sum)
+ .onClose(ex.apply("After pairMap"))
+ .append(4)
+ .onClose(ex.apply("After append"))
+ .prepend(Stream.of(5).onClose(ex.apply("Prepended Stream")))
+ .prepend(StreamEx.of(6).onClose(ex.apply("Prepended StreamEx")));
+ assertEquals(Arrays.asList(6, 5, 6, 10, 4), stream.toList());
+ try {
+ stream.close();
+ } 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(
+ Throwable::getMessage).toList());
+ assertTrue(flag.get());
+ return;
+ }
+ fail("No exception");
+ }
+
+ @Test
+ public void testChain() {
+ assertArrayEquals(new double[] { 2, 2, 6, 2, 6 },
+ IntStreamEx.of(3, 4, 5).chain(IntStreamEx::boxed)
+ .chain(s -> s.flatMapToLong(LongStreamEx::range))
+ .chain(s -> s.filter(n -> n % 2 != 0).asDoubleStream())
+ .chain(s -> s.map(x -> x * 2)).toArray(), 0.0);
+ }
+}
diff --git a/src/test/java/one/util/streamex/CustomPoolTest.java b/src/test/java/one/util/streamex/api/CustomPoolTest.java
similarity index 98%
rename from src/test/java/one/util/streamex/CustomPoolTest.java
rename to src/test/java/one/util/streamex/api/CustomPoolTest.java
index 10949213..890c58a4 100644
--- a/src/test/java/one/util/streamex/CustomPoolTest.java
+++ b/src/test/java/one/util/streamex/api/CustomPoolTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2015, 2019 StreamEx contributors
+ * Copyright 2015, 2020 StreamEx contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package one.util.streamex;
+package one.util.streamex.api;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
@@ -37,6 +37,13 @@
import org.junit.Test;
import org.junit.runners.MethodSorters;
+import one.util.streamex.DoubleStreamEx;
+import one.util.streamex.EntryStream;
+import one.util.streamex.IntStreamEx;
+import one.util.streamex.LongStreamEx;
+import one.util.streamex.MoreCollectors;
+import one.util.streamex.StreamEx;
+
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
diff --git a/src/test/java/one/util/streamex/DoubleCollectorTest.java b/src/test/java/one/util/streamex/api/DoubleCollectorTest.java
similarity index 96%
rename from src/test/java/one/util/streamex/DoubleCollectorTest.java
rename to src/test/java/one/util/streamex/api/DoubleCollectorTest.java
index cd955238..e2de795b 100644
--- a/src/test/java/one/util/streamex/DoubleCollectorTest.java
+++ b/src/test/java/one/util/streamex/api/DoubleCollectorTest.java
@@ -1,174 +1,180 @@
-/*
- * Copyright 2015, 2019 StreamEx contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package one.util.streamex;
-
-import java.util.Map;
-import java.util.OptionalDouble;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-
-/**
- * @author Tagir Valeev
- */
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class DoubleCollectorTest {
- @Test
- public void testJoining() {
- String expected = IntStream.range(0, 10000).asDoubleStream().mapToObj(String::valueOf).collect(
- Collectors.joining(", "));
- assertEquals(expected, IntStreamEx.range(10000).asDoubleStream().collect(DoubleCollector.joining(", ")));
- assertEquals(expected, IntStreamEx.range(10000).asDoubleStream().parallel().collect(
- DoubleCollector.joining(", ")));
- String expected2 = IntStreamEx.range(0, 1000).asDoubleStream().boxed().toList().toString();
- assertEquals(expected2, IntStreamEx.range(1000).asDoubleStream().collect(
- DoubleCollector.joining(", ", "[", "]")));
- assertEquals(expected2, IntStreamEx.range(1000).asDoubleStream().parallel().collect(
- DoubleCollector.joining(", ", "[", "]")));
- }
-
- @Test
- public void testCounting() {
- assertEquals(5000L, (long) IntStreamEx.range(10000).asDoubleStream().atLeast(5000).collect(
- DoubleCollector.counting()));
- assertEquals(5000L, (long) IntStreamEx.range(10000).asDoubleStream().parallel().atLeast(5000).collect(
- DoubleCollector.counting()));
- assertEquals(5000, (int) IntStreamEx.range(10000).asDoubleStream().atLeast(5000).collect(
- DoubleCollector.countingInt()));
- assertEquals(5000, (int) IntStreamEx.range(10000).asDoubleStream().parallel().atLeast(5000).collect(
- DoubleCollector.countingInt()));
- }
-
- @Test
- public void testSumming() {
- assertEquals(3725, IntStreamEx.range(100).asDoubleStream().atLeast(50).collect(DoubleCollector.summing()), 0.0);
- assertEquals(3725, IntStreamEx.range(100).asDoubleStream().parallel().atLeast(50).collect(
- DoubleCollector.summing()), 0.0);
- }
-
- @Test
- public void testMin() {
- assertEquals(50, IntStreamEx.range(100).asDoubleStream().atLeast(50).collect(DoubleCollector.min())
- .getAsDouble(), 0.0);
- assertEquals(50, IntStreamEx.range(100).asDoubleStream().atLeast(50).collect(
- DoubleCollector.min().andThen(OptionalDouble::getAsDouble)), 0.0);
- assertFalse(IntStreamEx.range(100).asDoubleStream().atLeast(200).collect(DoubleCollector.min()).isPresent());
- }
-
- @Test
- public void testMax() {
- assertEquals(99, IntStreamEx.range(100).asDoubleStream().atLeast(50).collect(DoubleCollector.max())
- .getAsDouble(), 0.0);
- assertEquals(99, IntStreamEx.range(100).asDoubleStream().parallel().atLeast(50).collect(DoubleCollector.max())
- .getAsDouble(), 0.0);
- assertFalse(IntStreamEx.range(100).asDoubleStream().atLeast(200).collect(DoubleCollector.max()).isPresent());
- }
-
- @Test
- public void testToArray() {
- assertArrayEquals(new double[] { 0, 1, 2, 3, 4 }, IntStreamEx.of(0, 1, 2, 3, 4).asDoubleStream().collect(
- DoubleCollector.toArray()), 0.0);
- assertArrayEquals(IntStreamEx.range(1000).asDoubleStream().toFloatArray(), IntStreamEx.range(1000).parallel()
- .asDoubleStream().collect(DoubleCollector.toFloatArray()), 0.0f);
- }
-
- @Test
- public void testPartitioning() {
- double[] expectedEven = IntStream.range(0, 1000).asDoubleStream().map(i -> i * 2).toArray();
- double[] expectedOdd = IntStream.range(0, 1000).asDoubleStream().map(i -> i * 2 + 1).toArray();
- Map oddEven = IntStreamEx.range(2000).asDoubleStream().collect(
- DoubleCollector.partitioningBy(i -> i % 2 == 0));
- assertArrayEquals(expectedEven, oddEven.get(true), 0.0);
- assertArrayEquals(expectedOdd, oddEven.get(false), 0.0);
- oddEven = IntStreamEx.range(2000).asDoubleStream().parallel().collect(
- DoubleCollector.partitioningBy(i -> i % 2 == 0));
- assertArrayEquals(expectedEven, oddEven.get(true), 0.0);
- assertArrayEquals(expectedOdd, oddEven.get(false), 0.0);
- }
-
- @Test
- public void testGroupingBy() {
- Map collected = IntStreamEx.range(2000).asDoubleStream().collect(
- DoubleCollector.groupingBy(i -> i % 3));
- for (double i = 0; i < 3; i++) {
- double rem = i;
- assertArrayEquals(IntStream.range(0, 2000).asDoubleStream().filter(a -> a % 3 == rem).toArray(), collected
- .get(i), 0.0);
- }
- collected = IntStreamEx.range(2000).asDoubleStream().parallel().collect(DoubleCollector.groupingBy(i -> i % 3));
- for (double i = 0; i < 3; i++) {
- double rem = i;
- assertArrayEquals(IntStream.range(0, 2000).asDoubleStream().filter(a -> a % 3 == rem).toArray(), collected
- .get(i), 0.0);
- }
- }
-
- @Test
- public void testAsCollector() {
- assertEquals(499.5, IntStream.range(0, 1000).asDoubleStream().boxed().collect(DoubleCollector.summarizing())
- .getAverage(), 0.000001);
- assertEquals(499.5, IntStream.range(0, 1000).parallel().asDoubleStream().boxed().collect(
- DoubleCollector.summarizing()).getAverage(), 0.000001);
- }
-
- @Test
- public void testAdaptor() {
- assertEquals(499.5, IntStreamEx.range(1000).asDoubleStream().collect(
- DoubleCollector.of(DoubleCollector.summarizing())).getAverage(), 0.000001);
- assertEquals(499.5, IntStreamEx.range(1000).parallel().asDoubleStream().collect(
- DoubleCollector.of(Collectors.summarizingDouble(Double::doubleValue))).getAverage(), 0.000001);
- }
-
- @Test
- public void testReducing() {
- assertEquals(7.0, DoubleStreamEx.of(1.0, 2.0, 3.5).collect(DoubleCollector.reducing(1.0, (a, b) -> a * b)), 0.0);
- assertEquals(7.0, DoubleStreamEx.of(1.0, 2.0, 3.5).parallel().collect(
- DoubleCollector.reducing(1.0, (a, b) -> a * b)), 0.0);
- }
-
- @Test
- public void testMapping() {
- assertEquals(10100.0, IntStreamEx.rangeClosed(0, 100).asDoubleStream().collect(
- DoubleCollector.mapping(x -> x * 2, DoubleCollector.summing())), 0.0);
-
- assertArrayEquals(LongStreamEx.of(1, 1, 2, 3).toArray(), DoubleStreamEx.of(0.8, 1.3, 1.7, 2.9).collect(
- DoubleCollector.mappingToObj(Math::round, LongCollector.toArray())));
- }
-
- @Test
- public void testAveraging() {
- assertFalse(DoubleStreamEx.empty().collect(DoubleCollector.averaging()).isPresent());
- assertEquals(1.0,
- DoubleStreamEx.of(0.0, 0.5, 1.0, 1.5, 2.0).collect(DoubleCollector.averaging()).getAsDouble(), 0.0);
- }
-
- @Test
- public void testToBooleanArray() {
- assertArrayEquals(new boolean[0], DoubleStreamEx.empty().collect(DoubleCollector.toBooleanArray(x -> true)));
- boolean[] expected = new boolean[] { true, false, false, true };
- assertArrayEquals(expected, DoubleStreamEx.of(1.0, 1.5, 2.7, 3.0).collect(
- DoubleCollector.toBooleanArray(x -> Math.floor(x) == x)));
- assertArrayEquals(expected, DoubleStreamEx.of(1.0, 1.5, 2.7, 3.0).parallel().collect(
- DoubleCollector.toBooleanArray(x -> Math.floor(x) == x)));
- }
-}
+/*
+ * Copyright 2015, 2020 StreamEx contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package one.util.streamex.api;
+
+import java.util.Map;
+import java.util.OptionalDouble;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runners.MethodSorters;
+
+import one.util.streamex.DoubleCollector;
+import one.util.streamex.DoubleStreamEx;
+import one.util.streamex.IntStreamEx;
+import one.util.streamex.LongCollector;
+import one.util.streamex.LongStreamEx;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+
+/**
+ * @author Tagir Valeev
+ */
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class DoubleCollectorTest {
+ @Test
+ public void testJoining() {
+ String expected = IntStream.range(0, 10000).asDoubleStream().mapToObj(String::valueOf).collect(
+ Collectors.joining(", "));
+ assertEquals(expected, IntStreamEx.range(10000).asDoubleStream().collect(DoubleCollector.joining(", ")));
+ assertEquals(expected, IntStreamEx.range(10000).asDoubleStream().parallel().collect(
+ DoubleCollector.joining(", ")));
+ String expected2 = IntStreamEx.range(0, 1000).asDoubleStream().boxed().toList().toString();
+ assertEquals(expected2, IntStreamEx.range(1000).asDoubleStream().collect(
+ DoubleCollector.joining(", ", "[", "]")));
+ assertEquals(expected2, IntStreamEx.range(1000).asDoubleStream().parallel().collect(
+ DoubleCollector.joining(", ", "[", "]")));
+ }
+
+ @Test
+ public void testCounting() {
+ assertEquals(5000L, (long) IntStreamEx.range(10000).asDoubleStream().atLeast(5000).collect(
+ DoubleCollector.counting()));
+ assertEquals(5000L, (long) IntStreamEx.range(10000).asDoubleStream().parallel().atLeast(5000).collect(
+ DoubleCollector.counting()));
+ assertEquals(5000, (int) IntStreamEx.range(10000).asDoubleStream().atLeast(5000).collect(
+ DoubleCollector.countingInt()));
+ assertEquals(5000, (int) IntStreamEx.range(10000).asDoubleStream().parallel().atLeast(5000).collect(
+ DoubleCollector.countingInt()));
+ }
+
+ @Test
+ public void testSumming() {
+ assertEquals(3725, IntStreamEx.range(100).asDoubleStream().atLeast(50).collect(DoubleCollector.summing()), 0.0);
+ assertEquals(3725, IntStreamEx.range(100).asDoubleStream().parallel().atLeast(50).collect(
+ DoubleCollector.summing()), 0.0);
+ }
+
+ @Test
+ public void testMin() {
+ assertEquals(50, IntStreamEx.range(100).asDoubleStream().atLeast(50).collect(DoubleCollector.min())
+ .getAsDouble(), 0.0);
+ assertEquals(50, IntStreamEx.range(100).asDoubleStream().atLeast(50).collect(
+ DoubleCollector.min().andThen(OptionalDouble::getAsDouble)), 0.0);
+ assertFalse(IntStreamEx.range(100).asDoubleStream().atLeast(200).collect(DoubleCollector.min()).isPresent());
+ }
+
+ @Test
+ public void testMax() {
+ assertEquals(99, IntStreamEx.range(100).asDoubleStream().atLeast(50).collect(DoubleCollector.max())
+ .getAsDouble(), 0.0);
+ assertEquals(99, IntStreamEx.range(100).asDoubleStream().parallel().atLeast(50).collect(DoubleCollector.max())
+ .getAsDouble(), 0.0);
+ assertFalse(IntStreamEx.range(100).asDoubleStream().atLeast(200).collect(DoubleCollector.max()).isPresent());
+ }
+
+ @Test
+ public void testToArray() {
+ assertArrayEquals(new double[] { 0, 1, 2, 3, 4 }, IntStreamEx.of(0, 1, 2, 3, 4).asDoubleStream().collect(
+ DoubleCollector.toArray()), 0.0);
+ assertArrayEquals(IntStreamEx.range(1000).asDoubleStream().toFloatArray(), IntStreamEx.range(1000).parallel()
+ .asDoubleStream().collect(DoubleCollector.toFloatArray()), 0.0f);
+ }
+
+ @Test
+ public void testPartitioning() {
+ double[] expectedEven = IntStream.range(0, 1000).asDoubleStream().map(i -> i * 2).toArray();
+ double[] expectedOdd = IntStream.range(0, 1000).asDoubleStream().map(i -> i * 2 + 1).toArray();
+ Map oddEven = IntStreamEx.range(2000).asDoubleStream().collect(
+ DoubleCollector.partitioningBy(i -> i % 2 == 0));
+ assertArrayEquals(expectedEven, oddEven.get(true), 0.0);
+ assertArrayEquals(expectedOdd, oddEven.get(false), 0.0);
+ oddEven = IntStreamEx.range(2000).asDoubleStream().parallel().collect(
+ DoubleCollector.partitioningBy(i -> i % 2 == 0));
+ assertArrayEquals(expectedEven, oddEven.get(true), 0.0);
+ assertArrayEquals(expectedOdd, oddEven.get(false), 0.0);
+ }
+
+ @Test
+ public void testGroupingBy() {
+ Map collected = IntStreamEx.range(2000).asDoubleStream().collect(
+ DoubleCollector.groupingBy(i -> i % 3));
+ for (double i = 0; i < 3; i++) {
+ double rem = i;
+ assertArrayEquals(IntStream.range(0, 2000).asDoubleStream().filter(a -> a % 3 == rem).toArray(), collected
+ .get(i), 0.0);
+ }
+ collected = IntStreamEx.range(2000).asDoubleStream().parallel().collect(DoubleCollector.groupingBy(i -> i % 3));
+ for (double i = 0; i < 3; i++) {
+ double rem = i;
+ assertArrayEquals(IntStream.range(0, 2000).asDoubleStream().filter(a -> a % 3 == rem).toArray(), collected
+ .get(i), 0.0);
+ }
+ }
+
+ @Test
+ public void testAsCollector() {
+ assertEquals(499.5, IntStream.range(0, 1000).asDoubleStream().boxed().collect(DoubleCollector.summarizing())
+ .getAverage(), 0.000001);
+ assertEquals(499.5, IntStream.range(0, 1000).parallel().asDoubleStream().boxed().collect(
+ DoubleCollector.summarizing()).getAverage(), 0.000001);
+ }
+
+ @Test
+ public void testAdaptor() {
+ assertEquals(499.5, IntStreamEx.range(1000).asDoubleStream().collect(
+ DoubleCollector.of(DoubleCollector.summarizing())).getAverage(), 0.000001);
+ assertEquals(499.5, IntStreamEx.range(1000).parallel().asDoubleStream().collect(
+ DoubleCollector.of(Collectors.summarizingDouble(Double::doubleValue))).getAverage(), 0.000001);
+ }
+
+ @Test
+ public void testReducing() {
+ assertEquals(7.0, DoubleStreamEx.of(1.0, 2.0, 3.5).collect(DoubleCollector.reducing(1.0, (a, b) -> a * b)), 0.0);
+ assertEquals(7.0, DoubleStreamEx.of(1.0, 2.0, 3.5).parallel().collect(
+ DoubleCollector.reducing(1.0, (a, b) -> a * b)), 0.0);
+ }
+
+ @Test
+ public void testMapping() {
+ assertEquals(10100.0, IntStreamEx.rangeClosed(0, 100).asDoubleStream().collect(
+ DoubleCollector.mapping(x -> x * 2, DoubleCollector.summing())), 0.0);
+
+ assertArrayEquals(LongStreamEx.of(1, 1, 2, 3).toArray(), DoubleStreamEx.of(0.8, 1.3, 1.7, 2.9).collect(
+ DoubleCollector.mappingToObj(Math::round, LongCollector.toArray())));
+ }
+
+ @Test
+ public void testAveraging() {
+ assertFalse(DoubleStreamEx.empty().collect(DoubleCollector.averaging()).isPresent());
+ assertEquals(1.0,
+ DoubleStreamEx.of(0.0, 0.5, 1.0, 1.5, 2.0).collect(DoubleCollector.averaging()).getAsDouble(), 0.0);
+ }
+
+ @Test
+ public void testToBooleanArray() {
+ assertArrayEquals(new boolean[0], DoubleStreamEx.empty().collect(DoubleCollector.toBooleanArray(x -> true)));
+ boolean[] expected = new boolean[] { true, false, false, true };
+ assertArrayEquals(expected, DoubleStreamEx.of(1.0, 1.5, 2.7, 3.0).collect(
+ DoubleCollector.toBooleanArray(x -> Math.floor(x) == x)));
+ assertArrayEquals(expected, DoubleStreamEx.of(1.0, 1.5, 2.7, 3.0).parallel().collect(
+ DoubleCollector.toBooleanArray(x -> Math.floor(x) == x)));
+ }
+}
diff --git a/src/test/java/one/util/streamex/DoubleStreamExTest.java b/src/test/java/one/util/streamex/api/DoubleStreamExTest.java
similarity index 97%
rename from src/test/java/one/util/streamex/DoubleStreamExTest.java
rename to src/test/java/one/util/streamex/api/DoubleStreamExTest.java
index 7022296a..ce569b07 100644
--- a/src/test/java/one/util/streamex/DoubleStreamExTest.java
+++ b/src/test/java/one/util/streamex/api/DoubleStreamExTest.java
@@ -1,537 +1,542 @@
-/*
- * Copyright 2015, 2019 StreamEx contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package one.util.streamex;
-
-import java.nio.DoubleBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.OptionalDouble;
-import java.util.PrimitiveIterator.OfDouble;
-import java.util.Random;
-import java.util.Scanner;
-import java.util.Spliterator;
-import java.util.Spliterators;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.function.DoubleBinaryOperator;
-import java.util.function.DoubleFunction;
-import java.util.function.DoubleToIntFunction;
-import java.util.function.DoubleToLongFunction;
-import java.util.function.DoubleUnaryOperator;
-import java.util.function.Function;
-import java.util.function.Supplier;
-import java.util.stream.DoubleStream;
-import java.util.stream.DoubleStream.Builder;
-import java.util.stream.LongStream;
-
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-
-import static one.util.streamex.TestHelpers.checkSpliterator;
-import static one.util.streamex.TestHelpers.streamEx;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-
-/**
- * @author Tagir Valeev
- */
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class DoubleStreamExTest {
- @Test
- public void testCreate() {
- assertArrayEquals(new double[] {}, DoubleStreamEx.empty().toArray(), 0.0);
- // double check is intended
- assertArrayEquals(new double[] {}, DoubleStreamEx.empty().toArray(), 0.0);
- assertArrayEquals(new double[] { 1 }, DoubleStreamEx.of(1).toArray(), 0.0);
- assertArrayEquals(new double[] { 1 }, DoubleStreamEx.of(OptionalDouble.of(1)).toArray(), 0.0);
- assertArrayEquals(new double[] {}, DoubleStreamEx.of(OptionalDouble.empty()).toArray(), 0.0);
- assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(1, 2, 3).toArray(), 0.0);
- assertArrayEquals(new double[] { 4, 6 }, DoubleStreamEx.of(new double[] { 2, 4, 6, 8, 10 }, 1, 3).toArray(),
- 0.0);
- assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(1.0f, 2.0f, 3.0f).toArray(), 0.0);
- assertArrayEquals(new double[] { 4, 6 }, DoubleStreamEx.of(new float[] { 2.0f, 4.0f, 6.0f, 8.0f, 10.0f }, 1, 3)
- .toArray(), 0.0);
- assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(DoubleStream.of(1, 2, 3)).toArray(), 0.0);
- assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(Arrays.asList(1.0, 2.0, 3.0)).toArray(), 0.0);
- assertArrayEquals(new double[] { 1, 2, 4, 8, 16 }, DoubleStreamEx.iterate(1, x -> x * 2).limit(5).toArray(),
- 0.0);
- assertArrayEquals(new double[] { 1, 1, 1, 1 }, DoubleStreamEx.generate(() -> 1).limit(4).toArray(), 0.0);
- assertArrayEquals(new double[] { 1, 1, 1, 1 }, DoubleStreamEx.constant(1.0, 4).toArray(), 0.0);
- assertEquals(10, DoubleStreamEx.of(new Random(), 10).count());
- assertArrayEquals(DoubleStreamEx.of(new Random(1), 10).toArray(), DoubleStreamEx.of(new Random(1)).limit(10)
- .toArray(), 0.0);
- assertTrue(DoubleStreamEx.of(new Random(), 100, 1, 10).allMatch(x -> x >= 1 && x < 10));
- assertArrayEquals(DoubleStreamEx.of(new Random(1), 100, 1, 10).toArray(), DoubleStreamEx.of(new Random(1), 1,
- 10).limit(100).toArray(), 0.0);
-
- DoubleStream stream = DoubleStreamEx.of(1, 2, 3);
- assertSame(stream, DoubleStreamEx.of(stream));
-
- assertArrayEquals(new double[] { 1, 5, 3 }, DoubleStreamEx.of(
- Spliterators.spliterator(new double[] { 1, 5, 3 }, 0)).toArray(), 0.0);
- assertArrayEquals(new double[] { 1, 5, 3 }, DoubleStreamEx.of(
- Spliterators.iterator(Spliterators.spliterator(new double[] { 1, 5, 3 }, 0))).toArray(), 0.0);
- assertArrayEquals(new double[0], DoubleStreamEx
- .of(Spliterators.iterator(Spliterators.emptyDoubleSpliterator())).parallel().toArray(), 0.0);
-
- assertArrayEquals(new double[] { 2, 4, 6 }, DoubleStreamEx.of(new Double[] { 2.0, 4.0, 6.0 }).toArray(), 0.0);
- }
-
- @Test
- public void testOfDoubleBuffer() {
- double[] data = LongStreamEx.range(100).asDoubleStream().toArray();
- assertArrayEquals(data, DoubleStreamEx.of(DoubleBuffer.wrap(data)).toArray(), 0.0);
- assertArrayEquals(LongStreamEx.range(50, 70).asDoubleStream().toArray(), DoubleStreamEx.of(DoubleBuffer.wrap(
- data, 50, 20)).toArray(), 0.0);
- assertArrayEquals(data, DoubleStreamEx.of(DoubleBuffer.wrap(data)).parallel().toArray(), 0.0);
- assertArrayEquals(LongStreamEx.range(50, 70).asDoubleStream().toArray(), DoubleStreamEx.of(DoubleBuffer.wrap(
- data, 50, 20)).parallel().toArray(), 0.0);
- }
-
- @Test
- public void testIterate() {
- assertArrayEquals(new double[] { 1, 2, 4, 8, 16 }, DoubleStreamEx.iterate(1, x -> x * 2).limit(5).toArray(),
- 0.0);
- assertArrayEquals(new double[] { 1, 2, 4, 8, 16, 32, 64 }, DoubleStreamEx.iterate(1, x -> x < 100, x -> x * 2)
- .toArray(), 0.0);
- assertEquals(0, DoubleStreamEx.iterate(0, x -> x < 0, x -> 1 / x).count());
- assertFalse(DoubleStreamEx.iterate(1, x -> x < 100, x -> x * 2).findFirst(x -> x == 10).isPresent());
- checkSpliterator("iterate", () -> DoubleStreamEx.iterate(1, x -> x < 100, x -> x * 2).spliterator());
- }
-
- @Test
- public void testBasics() {
- assertFalse(DoubleStreamEx.of(1).isParallel());
- assertTrue(DoubleStreamEx.of(1).parallel().isParallel());
- assertFalse(DoubleStreamEx.of(1).parallel().sequential().isParallel());
- AtomicInteger i = new AtomicInteger();
- try (DoubleStreamEx s = DoubleStreamEx.of(1).onClose(i::incrementAndGet)) {
- assertEquals(1, s.count());
- }
- assertEquals(1, i.get());
- assertEquals(6, IntStreamEx.range(0, 4).asDoubleStream().sum(), 0);
- assertEquals(3, IntStreamEx.range(0, 4).asDoubleStream().max().getAsDouble(), 0);
- assertEquals(0, IntStreamEx.range(0, 4).asDoubleStream().min().getAsDouble(), 0);
- assertEquals(1.5, IntStreamEx.range(0, 4).asDoubleStream().average().getAsDouble(), 0.000001);
- assertEquals(4, IntStreamEx.range(0, 4).asDoubleStream().summaryStatistics().getCount());
- assertArrayEquals(new double[] { 1, 2, 3 },
- IntStreamEx.range(0, 5).asDoubleStream().skip(1).limit(3).toArray(), 0.0);
- assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(3, 1, 2).sorted().toArray(), 0.0);
- assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(1, 2, 1, 3, 2).distinct().toArray(), 0.0);
- assertArrayEquals(new int[] { 2, 4, 6 }, IntStreamEx.range(1, 4).asDoubleStream().mapToInt(x -> (int) x * 2)
- .toArray());
- assertArrayEquals(new long[] { 2, 4, 6 }, IntStreamEx.range(1, 4).asDoubleStream().mapToLong(x -> (long) x * 2)
- .toArray());
- assertArrayEquals(new double[] { 2, 4, 6 }, IntStreamEx.range(1, 4).asDoubleStream().map(x -> x * 2).toArray(),
- 0.0);
- assertArrayEquals(new double[] { 1, 3 }, IntStreamEx.range(0, 5).asDoubleStream().filter(x -> x % 2 == 1)
- .toArray(), 0.0);
- assertEquals(6.0, DoubleStreamEx.of(1.0, 2.0, 3.0).reduce(Double::sum).getAsDouble(), 0.0);
- assertEquals(Long.MAX_VALUE, LongStreamEx.rangeClosed(1, Long.MAX_VALUE).asDoubleStream().spliterator()
- .getExactSizeIfKnown());
-
- assertArrayEquals(new double[] { 4, 2, 0, -2, -4 }, DoubleStreamEx.zip(new double[] { 5, 4, 3, 2, 1 },
- new double[] { 1, 2, 3, 4, 5 }, (a, b) -> a - b).toArray(), 0.0);
- assertEquals("1.0; 0.5; 0.25; 0.125", DoubleStreamEx.of(1.0, 0.5, 0.25, 0.125).mapToObj(String::valueOf)
- .joining("; "));
- List list = new ArrayList<>();
- DoubleStreamEx.of(1.0, 0.5, 0.25, 0.125).forEach(list::add);
- assertEquals(Arrays.asList(1.0, 0.5, 0.25, 0.125), list);
- list = new ArrayList<>();
- DoubleStreamEx.of(1.0, 0.5, 0.25, 0.125).parallel().forEachOrdered(list::add);
- assertEquals(Arrays.asList(1.0, 0.5, 0.25, 0.125), list);
-
- assertFalse(DoubleStreamEx.of(1.0, 2.0, 2.5).anyMatch(x -> x < 0.0));
- assertTrue(DoubleStreamEx.of(1.0, 2.0, 2.5).anyMatch(x -> x >= 2.5));
- assertTrue(DoubleStreamEx.of(1.0, 2.0, 2.5).noneMatch(x -> x < 0.0));
- assertFalse(DoubleStreamEx.of(1.0, 2.0, 2.5).noneMatch(x -> x >= 2.5));
- assertEquals(5.0, DoubleStreamEx.of(1.0, 2.0, 2.5).reduce(1, (a, b) -> a * b), 0.0);
-
- assertTrue(DoubleStreamEx.of(1, 2, 3).spliterator().hasCharacteristics(Spliterator.ORDERED));
- assertFalse(DoubleStreamEx.of(1, 2, 3).unordered().spliterator().hasCharacteristics(Spliterator.ORDERED));
-
- OfDouble iterator = DoubleStreamEx.of(1.0, 2.0, 3.0).iterator();
- assertEquals(1.0, iterator.next(), 0.0);
- assertEquals(2.0, iterator.next(), 0.0);
- assertEquals(3.0, iterator.next(), 0.0);
- assertFalse(iterator.hasNext());
- }
-
- @Test
- public void testForEach() {
- streamEx(() -> StreamEx.of(1, 2, 3), s -> {
- AtomicInteger count = new AtomicInteger(0);
- s.get().mapToDouble(Integer::intValue).forEach(v -> count.addAndGet((int) v));
- assertEquals(6, count.get());
- s.get().mapToDouble(Integer::intValue).pairMap((a, b) -> b - a).forEach(v -> count.addAndGet((int) v));
- assertEquals(8, count.get());
- });
- }
-
- @Test
- public void testFlatMap() {
- assertArrayEquals(new int[] { 1, 5, 2, 3, 3, 2, 0, 9 }, DoubleStreamEx.of(1.5, 2.3, 3.2, 0.9).flatMapToInt(
- x -> IntStreamEx.of((int) Math.floor(x), (int) (Math.round(10 * (x - Math.floor(x)))))).toArray());
- assertEquals("1:.:5:2:2:.:3:3:.:2:0:.:9", DoubleStreamEx.of(1.5, 22.3, 3.2, 0.9).flatMapToObj(
- x -> StreamEx.split(String.valueOf(x), "")).joining(":"));
-
- assertArrayEquals(new double[] { 0.0, 0.0, 1.0, 0.0, 1.0, 2.0 }, DoubleStreamEx.of(1, 2, 3).flatMap(
- x -> IntStreamEx.range((int) x).asDoubleStream()).toArray(), 0.0);
-
- assertArrayEquals(new long[] { 0x3FF0000000000000L, 0x3FF0000000000000L, 0x4000000000000000L,
- 0x4000000000000000L, 0x7FF8000000000000L, 0x7FF8000000000000L }, DoubleStreamEx.of(1, 2, Double.NaN)
- .flatMapToLong(x -> LongStream.of(Double.doubleToLongBits(x), Double.doubleToRawLongBits(x))).toArray());
- }
-
- @Test
- public void testPrepend() {
- assertArrayEquals(new double[] { -1, 0, 1, 2, 3 }, DoubleStreamEx.of(1, 2, 3).prepend(-1, 0).toArray(), 0.0);
- assertArrayEquals(new double[] { -1, 0, 1, 2, 3 }, DoubleStreamEx.of(1, 2, 3).prepend(DoubleStream.of(-1, 0))
- .toArray(), 0.0);
- DoubleStreamEx s = DoubleStreamEx.of(1, 2, 3);
- assertSame(s, s.prepend());
- }
-
- @Test
- public void testAppend() {
- assertArrayEquals(new double[] { 1, 2, 3, 4, 5 }, DoubleStreamEx.of(1, 2, 3).append(4, 5).toArray(), 0.0);
- assertArrayEquals(new double[] { 1, 2, 3, 4, 5 }, DoubleStreamEx.of(1, 2, 3).append(DoubleStream.of(4, 5))
- .toArray(), 0.0);
- DoubleStreamEx s = DoubleStreamEx.of(1, 2, 3);
- assertSame(s, s.append());
- }
-
- @Test
- public void testRanges() {
- assertArrayEquals(new double[] { 5, 4, Double.POSITIVE_INFINITY }, DoubleStreamEx.of(1, 5, 3, 4, -1,
- Double.POSITIVE_INFINITY).greater(3).toArray(), 0.0);
- assertArrayEquals(new double[] {}, DoubleStreamEx.of(1, 5, 3, 4, -1, Double.POSITIVE_INFINITY).greater(
- Double.POSITIVE_INFINITY).toArray(), 0.0);
- assertArrayEquals(new double[] { 5, 3, 4, Double.POSITIVE_INFINITY }, DoubleStreamEx.of(1, 5, 3, 4, -1,
- Double.POSITIVE_INFINITY).atLeast(3).toArray(), 0.0);
- assertArrayEquals(new double[] { Double.POSITIVE_INFINITY }, DoubleStreamEx.of(1, 5, 3, 4, -1,
- Double.POSITIVE_INFINITY).atLeast(Double.POSITIVE_INFINITY).toArray(), 0.0);
- assertArrayEquals(new double[] { 1, -1 }, DoubleStreamEx.of(1, 5, 3, 4, -1, Double.POSITIVE_INFINITY).less(3)
- .toArray(), 0.0);
- assertArrayEquals(new double[] { 1, 3, -1 }, DoubleStreamEx.of(1, 5, 3, 4, -1, Double.POSITIVE_INFINITY)
- .atMost(3).toArray(), 0.0);
- assertArrayEquals(new double[] { 1, 3, 4, -1 }, DoubleStreamEx.of(1, 5, 3, 4, -1, Double.POSITIVE_INFINITY)
- .atMost(4).toArray(), 0.0);
- }
-
- @Test
- public void testFind() {
- assertEquals(6.0, LongStreamEx.range(1, 10).asDoubleStream().findFirst(i -> i > 5).getAsDouble(), 0.0);
- assertFalse(LongStreamEx.range(1, 10).asDoubleStream().findAny(i -> i > 10).isPresent());
- }
-
- @Test
- public void testRemove() {
- assertArrayEquals(new double[] { 1, 2 }, DoubleStreamEx.of(1, 2, 3).remove(x -> x > 2).toArray(), 0.0);
- }
-
- @Test
- public void testSort() {
- assertArrayEquals(new double[] { 3, 2, 1 }, DoubleStreamEx.of(1, 2, 3).sortedByDouble(x -> -x).toArray(), 0.0);
- assertArrayEquals(new double[] { Double.NaN, Double.NaN, Double.POSITIVE_INFINITY, Double.MAX_VALUE, 1000, 1,
- Double.MIN_VALUE, 0, -0.0, -Double.MIN_VALUE * 3, -10, -Double.MAX_VALUE / 1.1, -Double.MAX_VALUE,
- Double.NEGATIVE_INFINITY }, DoubleStreamEx.of(0, 1, -Double.MIN_VALUE * 3, 1000, -10,
- -Double.MAX_VALUE, Double.POSITIVE_INFINITY, Double.NaN, Double.NEGATIVE_INFINITY, Double.NaN,
- Double.MAX_VALUE, -0.0, Double.MIN_VALUE, -Double.MAX_VALUE / 1.1).reverseSorted().toArray(), 0.0);
- assertArrayEquals(new double[] { 1, 10, 2, 21, 9 }, DoubleStreamEx.of(1, 10, 2, 9, 21)
- .sortedBy(String::valueOf).toArray(), 0.0);
-
- assertArrayEquals(new double[] { 0.4, 1.5, 1.3, 2.3, 2.1, 2.0, 3.7 }, DoubleStreamEx.of(1.5, 2.3, 1.3, 2.1,
- 3.7, 0.4, 2.0).sortedByInt(x -> (int) x).toArray(), 0.0);
-
- assertArrayEquals(new double[] { 0.4, 1.5, 1.3, 2.3, 2.1, 2.0, 3.7 }, DoubleStreamEx.of(1.5, 2.3, 1.3, 2.1,
- 3.7, 0.4, 2.0).sortedByLong(x -> (long) x).toArray(), 0.0);
- double nonCanonicalNan = Double.longBitsToDouble(0xfff8000000000001L);
- double nonCanonicalNan2 = Double.longBitsToDouble(0x7ff8000000000000L);
- assertTrue(Double.isNaN(nonCanonicalNan));
- assertTrue(Double.isNaN(nonCanonicalNan2));
- double[] data = {Double.NEGATIVE_INFINITY, 0.0, 1.0, Double.POSITIVE_INFINITY, Double.NaN, nonCanonicalNan,
- nonCanonicalNan2};
- double[] reverseData = {nonCanonicalNan, nonCanonicalNan2, Double.NaN, Double.POSITIVE_INFINITY, 1.0, 0.0,
- Double.NEGATIVE_INFINITY};
- assertArrayEquals(DoubleStreamEx.of(data).mapToLong(Double::doubleToRawLongBits).toArray(),
- DoubleStreamEx.of(data).sorted().mapToLong(Double::doubleToRawLongBits).toArray());
- assertArrayEquals(DoubleStreamEx.of(reverseData).mapToLong(Double::doubleToRawLongBits).toArray(),
- DoubleStreamEx.of(data).reverseSorted().mapToLong(Double::doubleToRawLongBits).toArray());
- }
-
- @SafeVarargs
- private static void checkEmpty(Function... fns) {
- int i = 0;
- for (Function fn : fns) {
- assertFalse("#" + i, fn.apply(DoubleStreamEx.empty()).isPresent());
- assertFalse("#" + i, fn.apply(DoubleStreamEx.of(1, 2, 3, 4).greater(5).parallel()).isPresent());
- assertEquals("#" + i, 10, fn.apply(DoubleStreamEx.of(1, 1, 1, 1, 10, 10, 10, 10).greater(5).parallel())
- .getAsDouble(), 0.0);
- i++;
- }
- }
-
- @Test
- public void testMinMax() {
- checkEmpty(s -> s.maxBy(Double::valueOf), s -> s.maxByInt(x -> (int) x), s -> s.maxByLong(x -> (long) x),
- s -> s.maxByDouble(x -> x), s -> s.minBy(Double::valueOf), s -> s.minByInt(x -> (int) x), s -> s
- .minByLong(x -> (long) x), s -> s.minByDouble(x -> x));
- assertEquals(9, IntStreamEx.range(5, 12).asDoubleStream().max(
- Comparator.comparing(String::valueOf)).getAsDouble(), 0.0);
- assertEquals(10, IntStreamEx.range(5, 12).asDoubleStream().min(
- Comparator.comparing(String::valueOf)).getAsDouble(), 0.0);
- assertEquals(9, IntStreamEx.range(5, 12).asDoubleStream().maxBy(String::valueOf).getAsDouble(), 0.0);
- assertEquals(10, IntStreamEx.range(5, 12).asDoubleStream().minBy(String::valueOf).getAsDouble(), 0.0);
- assertEquals(5, IntStreamEx.range(5, 12).asDoubleStream().maxByDouble(x -> 1.0 / x).getAsDouble(), 0.0);
- assertEquals(11, IntStreamEx.range(5, 12).asDoubleStream().minByDouble(x -> 1.0 / x).getAsDouble(), 0.0);
- assertEquals(29.0, DoubleStreamEx.of(15, 8, 31, 47, 19, 29).maxByInt(x -> (int) (x % 10 * 10 + x / 10))
- .getAsDouble(), 0.0);
- assertEquals(31.0, DoubleStreamEx.of(15, 8, 31, 47, 19, 29).minByInt(x -> (int) (x % 10 * 10 + x / 10))
- .getAsDouble(), 0.0);
- assertEquals(29.0, DoubleStreamEx.of(15, 8, 31, 47, 19, 29).maxByLong(x -> (long) (x % 10 * 10 + x / 10))
- .getAsDouble(), 0.0);
- assertEquals(31.0, DoubleStreamEx.of(15, 8, 31, 47, 19, 29).minByLong(x -> (long) (x % 10 * 10 + x / 10))
- .getAsDouble(), 0.0);
-
- Supplier s = () -> DoubleStreamEx.of(1, 50, 120, 35, 130, 12, 0);
- DoubleToIntFunction intKey = x -> String.valueOf(x).length();
- DoubleToLongFunction longKey = x -> String.valueOf(x).length();
- DoubleUnaryOperator doubleKey = x -> String.valueOf(x).length();
- DoubleFunction objKey = x -> String.valueOf(x).length();
- List> minFns = Arrays.asList(is -> is.minByInt(intKey), is -> is
- .minByLong(longKey), is -> is.minByDouble(doubleKey), is -> is.minBy(objKey));
- List> maxFns = Arrays.asList(is -> is.maxByInt(intKey), is -> is
- .maxByLong(longKey), is -> is.maxByDouble(doubleKey), is -> is.maxBy(objKey));
- minFns.forEach(fn -> assertEquals(1, fn.apply(s.get()).getAsDouble(), 0.0));
- minFns.forEach(fn -> assertEquals(1, fn.apply(s.get().parallel()).getAsDouble(), 0.0));
- maxFns.forEach(fn -> assertEquals(120, fn.apply(s.get()).getAsDouble(), 0.0));
- maxFns.forEach(fn -> assertEquals(120, fn.apply(s.get().parallel()).getAsDouble(), 0.0));
- }
-
- @Test
- public void testPairMap() {
- assertEquals(0, DoubleStreamEx.of().pairMap(Double::sum).count());
- assertEquals(0, DoubleStreamEx.of(1.0).pairMap(Double::sum).count());
- int[] data = new Random(1).ints(1000, 1, 1000).toArray();
- double[] expected = new double[data.length - 1];
- for (int i = 0; i < expected.length; i++)
- expected[i] = (data[i + 1] - data[i]) * 1.23;
- double[] result = IntStreamEx.of(data).parallel().asDoubleStream().pairMap((a, b) -> (b - a) * 1.23).toArray();
- assertArrayEquals(expected, result, 0.0);
- result = IntStreamEx.of(data).asDoubleStream().pairMap((a, b) -> (b - a) * 1.23).toArray();
- assertArrayEquals(expected, result, 0.0);
- assertEquals(984.0, IntStreamEx.of(data).asDoubleStream().parallel().pairMap((a, b) -> Math.abs(a - b)).max()
- .getAsDouble(), 0.0);
- assertArrayEquals(new double[] { 1.0, 1.0 }, DoubleStreamEx.of(1.0, 2.0, 3.0).append().parallel().pairMap(
- (a, b) -> b - a).toArray(), 0.0);
-
- assertArrayEquals(LongStreamEx.range(1, 100).asDoubleStream().toArray(), LongStreamEx.range(100).map(
- i -> i * (i + 1) / 2).append(LongStream.empty()).asDoubleStream().parallel().pairMap((a, b) -> b - a)
- .toArray(), 0.0);
- assertArrayEquals(LongStreamEx.range(1, 100).asDoubleStream().toArray(), LongStreamEx.range(100).map(
- i -> i * (i + 1) / 2).prepend(LongStream.empty()).asDoubleStream().parallel().pairMap((a, b) -> b - a)
- .toArray(), 0.0);
-
- assertEquals(1, LongStreamEx.range(1000).mapToDouble(x -> x * x).pairMap((a, b) -> b - a).pairMap(
- (a, b) -> b - a).distinct().count());
-
- assertFalse(LongStreamEx.range(1000).asDoubleStream().greater(2000).parallel().pairMap((a, b) -> a).findFirst()
- .isPresent());
- }
-
- @Test
- public void testToFloatArray() {
- float[] expected = new float[10000];
- for (int i = 0; i < expected.length; i++)
- expected[i] = i;
- assertArrayEquals(expected, IntStreamEx.range(0, 10000).asDoubleStream().toFloatArray(), 0.0f);
- assertArrayEquals(expected, IntStreamEx.range(0, 10000).asDoubleStream().parallel().toFloatArray(), 0.0f);
- assertArrayEquals(expected, IntStreamEx.range(0, 10000).asDoubleStream().greater(-1).toFloatArray(), 0.0f);
- assertArrayEquals(expected, IntStreamEx.range(0, 10000).asDoubleStream().parallel().greater(-1).toFloatArray(),
- 0.0f);
- // Test when resize of internal buffer is not required on addAll (buffer size = 128)
- assertArrayEquals(Arrays.copyOf(expected, 100),
- IntStreamEx.range(0, 100).asDoubleStream().parallel().toFloatArray(), 0.0f);
- }
-
- @Test
- public void testJoining() {
- assertEquals("0.4,5.0,3.6,4.8", DoubleStreamEx.of(0.4, 5.0, 3.6, 4.8).joining(","));
- assertEquals("0.4,5.0,3.6,4.8", DoubleStreamEx.of(0.4, 5.0, 3.6, 4.8).parallel().joining(","));
- assertEquals("[0.4,5.0,3.6,4.8]", DoubleStreamEx.of(0.4, 5.0, 3.6, 4.8).joining(",", "[", "]"));
- assertEquals("[0.4,5.0,3.6,4.8]", DoubleStreamEx.of(0.4, 5.0, 3.6, 4.8).parallel().joining(",", "[", "]"));
- }
-
- @Test
- public void testMapToEntry() {
- Map> map = DoubleStreamEx.of(0.3, 0.5, 1.3, 0.7, 1.9, 2.1).mapToEntry(x -> (int) x,
- x -> x).grouping();
- assertEquals(Arrays.asList(0.3, 0.5, 0.7), map.get(0));
- assertEquals(Arrays.asList(1.3, 1.9), map.get(1));
- assertEquals(Arrays.asList(2.1), map.get(2));
- }
-
- @Test
- public void testTakeWhile() {
- assertArrayEquals(LongStreamEx.range(100).asDoubleStream().toArray(), DoubleStreamEx.iterate(0, i -> i + 1)
- .takeWhile(i -> i < 100).toArray(), 0.0);
- assertEquals(0, DoubleStreamEx.iterate(0, i -> i + 1).takeWhile(i -> i < 0).count());
- assertEquals(1, DoubleStreamEx.of(1, 3, 2).takeWhile(i -> i < 3).count());
- assertEquals(3, DoubleStreamEx.of(1, 2, 3).takeWhile(i -> i < 100).count());
- }
-
- @Test
- public void testTakeWhileInclusive() {
- assertArrayEquals(LongStreamEx.range(101).asDoubleStream().toArray(), DoubleStreamEx.iterate(0, i -> i + 1)
- .takeWhileInclusive(i -> i < 100).toArray(), 0.0);
- assertEquals(1, DoubleStreamEx.iterate(0, i -> i + 1).takeWhileInclusive(i -> i < 0).count());
- assertEquals(2, DoubleStreamEx.of(1, 3, 2).takeWhileInclusive(i -> i < 3).count());
- assertEquals(3, DoubleStreamEx.of(1, 2, 3).takeWhileInclusive(i -> i < 100).count());
- }
-
- @Test
- public void testDropWhile() {
- assertArrayEquals(new double[] { 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }, LongStreamEx.range(100).asDoubleStream()
- .dropWhile(i -> i % 10 < 5).limit(10).toArray(), 0.0);
- assertEquals(100, LongStreamEx.range(100).asDoubleStream().sorted().dropWhile(i -> i % 10 < 0).count());
- assertEquals(0, LongStreamEx.range(100).asDoubleStream().dropWhile(i -> i % 10 < 10).count());
- assertEquals(OptionalDouble.of(0), LongStreamEx.range(100).asDoubleStream().dropWhile(i -> i % 10 < 0).findFirst());
- assertEquals(OptionalDouble.empty(), LongStreamEx.range(100).asDoubleStream().dropWhile(i -> i % 10 < 10).findFirst());
-
- java.util.Spliterator.OfDouble spltr = LongStreamEx.range(100).asDoubleStream().dropWhile(i -> i % 10 < 1).spliterator();
- assertTrue(spltr.tryAdvance((double x) -> assertEquals(1, x, 0.0)));
- Builder builder = DoubleStream.builder();
- spltr.forEachRemaining(builder);
- assertArrayEquals(LongStreamEx.range(2, 100).asDoubleStream().toArray(), builder.build().toArray(), 0.0);
- }
-
- @Test
- public void testIndexOf() {
- assertEquals(11, LongStreamEx.range(50, 100).asDoubleStream().indexOf(x -> x > 60).getAsLong());
- assertFalse(LongStreamEx.range(50, 100).asDoubleStream().indexOf(x -> x < 0).isPresent());
- assertEquals(11, LongStreamEx.range(50, 100).asDoubleStream().parallel().indexOf(x -> x > 60).getAsLong());
- assertFalse(LongStreamEx.range(50, 100).asDoubleStream().parallel().indexOf(x -> x < 0).isPresent());
- }
-
- @Test
- public void testFoldLeft() {
- // non-associative
- DoubleBinaryOperator accumulator = (x, y) -> (x + y) * (x + y);
- assertEquals(2322576, DoubleStreamEx.constant(3, 4).foldLeft(accumulator).orElse(-1), 0.0);
- assertEquals(2322576, DoubleStreamEx.constant(3, 4).parallel().foldLeft(accumulator).orElse(-1), 0.0);
- assertFalse(DoubleStreamEx.empty().foldLeft(accumulator).isPresent());
- assertEquals(144, DoubleStreamEx.of(1, 2, 3).foldLeft(0.0, accumulator), 144);
- assertEquals(144, DoubleStreamEx.of(1, 2, 3).parallel().foldLeft(0.0, accumulator), 144);
- }
-
- @Test
- public void testMapFirstLast() {
- assertArrayEquals(new double[] { -1, 2, 3, 4, 7 }, DoubleStreamEx.of(1, 2, 3, 4, 5).mapFirst(x -> x - 2.0)
- .mapLast(x -> x + 2.0).toArray(), 0.0);
- }
-
- @Test
- public void testPeekFirst() {
- double[] input = {1, 10, 100, 1000};
-
- AtomicReference firstElement = new AtomicReference<>();
- assertArrayEquals(new double[] {10, 100, 1000}, DoubleStreamEx.of(input).peekFirst(firstElement::set).skip(1).toArray(), 0.0);
- assertEquals(1, firstElement.get(), 0.0);
-
- assertArrayEquals(new double[] {10, 100, 1000}, DoubleStreamEx.of(input).skip(1).peekFirst(firstElement::set).toArray(), 0.0);
- assertEquals(10, firstElement.get(), 0.0);
-
- firstElement.set(-1.0);
- assertArrayEquals(new double[] {}, DoubleStreamEx.of(input).skip(4).peekFirst(firstElement::set).toArray(), 0.0);
- assertEquals(-1, firstElement.get(), 0.0);
- }
-
- @Test
- public void testPeekLast() {
- double[] input = {1, 10, 100, 1000};
- AtomicReference lastElement = new AtomicReference<>();
- assertArrayEquals(new double[] {1, 10, 100}, DoubleStreamEx.of(input).peekLast(lastElement::set).limit(3).toArray(), 0.0);
- assertNull(lastElement.get());
-
- assertArrayEquals(new double[] { 1, 10, 100 }, DoubleStreamEx.of(input).less(1000).peekLast(lastElement::set)
- .limit(3).toArray(), 0.0);
- assertEquals(100, lastElement.get(), 0.0);
-
- assertArrayEquals(input, DoubleStreamEx.of(input).peekLast(lastElement::set).limit(4).toArray(), 0.0);
- assertEquals(1000, lastElement.get(), 0.0);
-
- assertArrayEquals(new double[] {1, 10, 100}, DoubleStreamEx.of(input).limit(3).peekLast(lastElement::set).toArray(), 0.0);
- assertEquals(100, lastElement.get(), 0.0);
- }
-
- @Test
- public void testScanLeft() {
- assertArrayEquals(new double[] { 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 }, LongStreamEx.range(10).asDoubleStream()
- .scanLeft(Double::sum), 0.0);
- assertArrayEquals(new double[] { 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 }, LongStreamEx.range(10).asDoubleStream()
- .parallel().scanLeft(Double::sum), 0.0);
- assertArrayEquals(new double[] { 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 }, LongStreamEx.range(10).asDoubleStream()
- .filter(x -> true).scanLeft(Double::sum), 0.0);
- assertArrayEquals(new double[] { 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 }, LongStreamEx.range(10).asDoubleStream()
- .filter(x -> true).parallel().scanLeft(Double::sum), 0.0);
- assertArrayEquals(new double[] { 1, 1, 2, 6, 24, 120 }, LongStreamEx.rangeClosed(1, 5).asDoubleStream()
- .scanLeft(1, (a, b) -> a * b), 0.0);
- assertArrayEquals(new double[] { 1, 1, 2, 6, 24, 120 }, LongStreamEx.rangeClosed(1, 5).asDoubleStream()
- .parallel().scanLeft(1, (a, b) -> a * b), 0.0);
- }
-
- // Reads numbers from scanner stopping when non-number is encountered
- // leaving scanner in known state
- private static DoubleStreamEx scannerDoubles(Scanner sc) {
- return DoubleStreamEx.produce(action -> {
- if (sc.hasNextDouble())
- action.accept(sc.nextDouble());
- return sc.hasNextDouble();
- });
- }
-
- @Test
- public void testProduce() {
- Scanner sc = new Scanner("1.0 2.5 3 -4.6 test");
- sc.useLocale(Locale.ENGLISH);
- assertArrayEquals(new double[] {1, 2.5, 3, -4.6}, scannerDoubles(sc).stream().toArray(), 0.0);
- assertEquals("test", sc.next());
- }
-
- @Test
- public void testPrefix() {
- assertArrayEquals(new double[] { 1, 3, 6, 10, 20 }, DoubleStreamEx.of(1, 2, 3, 4, 10).prefix(Double::sum).toArray(), 0.0);
- assertEquals(OptionalDouble.of(10), DoubleStreamEx.of(1, 2, 3, 4, 10).prefix(Double::sum).findFirst(x -> x > 7));
- assertEquals(OptionalDouble.empty(), DoubleStreamEx.of(1, 2, 3, 4, 10).prefix(Double::sum).findFirst(x -> x > 20));
- }
-
- @Test
- public void testIntersperse() {
- assertArrayEquals(new double[] { 1, 0, 10, 0, 100, 0, 1000 }, DoubleStreamEx.of(1, 10, 100, 1000).intersperse(0)
- .toArray(), 0.0);
- assertEquals(0L, IntStreamEx.empty().intersperse(1).count());
- }
-}
+/*
+ * Copyright 2015, 2020 StreamEx contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package one.util.streamex.api;
+
+import java.nio.DoubleBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.OptionalDouble;
+import java.util.PrimitiveIterator.OfDouble;
+import java.util.Random;
+import java.util.Scanner;
+import java.util.Spliterator;
+import java.util.Spliterators;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.DoubleBinaryOperator;
+import java.util.function.DoubleFunction;
+import java.util.function.DoubleToIntFunction;
+import java.util.function.DoubleToLongFunction;
+import java.util.function.DoubleUnaryOperator;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.DoubleStream;
+import java.util.stream.DoubleStream.Builder;
+import java.util.stream.LongStream;
+
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runners.MethodSorters;
+
+import one.util.streamex.DoubleStreamEx;
+import one.util.streamex.IntStreamEx;
+import one.util.streamex.LongStreamEx;
+import one.util.streamex.StreamEx;
+
+import static one.util.streamex.TestHelpers.checkSpliterator;
+import static one.util.streamex.TestHelpers.streamEx;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * @author Tagir Valeev
+ */
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class DoubleStreamExTest {
+ @Test
+ public void testCreate() {
+ assertArrayEquals(new double[] {}, DoubleStreamEx.empty().toArray(), 0.0);
+ // double check is intended
+ assertArrayEquals(new double[] {}, DoubleStreamEx.empty().toArray(), 0.0);
+ assertArrayEquals(new double[] { 1 }, DoubleStreamEx.of(1).toArray(), 0.0);
+ assertArrayEquals(new double[] { 1 }, DoubleStreamEx.of(OptionalDouble.of(1)).toArray(), 0.0);
+ assertArrayEquals(new double[] {}, DoubleStreamEx.of(OptionalDouble.empty()).toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(1, 2, 3).toArray(), 0.0);
+ assertArrayEquals(new double[] { 4, 6 }, DoubleStreamEx.of(new double[] { 2, 4, 6, 8, 10 }, 1, 3).toArray(),
+ 0.0);
+ assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(1.0f, 2.0f, 3.0f).toArray(), 0.0);
+ assertArrayEquals(new double[] { 4, 6 }, DoubleStreamEx.of(new float[] { 2.0f, 4.0f, 6.0f, 8.0f, 10.0f }, 1, 3)
+ .toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(DoubleStream.of(1, 2, 3)).toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(Arrays.asList(1.0, 2.0, 3.0)).toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, 2, 4, 8, 16 }, DoubleStreamEx.iterate(1, x -> x * 2).limit(5).toArray(),
+ 0.0);
+ assertArrayEquals(new double[] { 1, 1, 1, 1 }, DoubleStreamEx.generate(() -> 1).limit(4).toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, 1, 1, 1 }, DoubleStreamEx.constant(1.0, 4).toArray(), 0.0);
+ assertEquals(10, DoubleStreamEx.of(new Random(), 10).count());
+ assertArrayEquals(DoubleStreamEx.of(new Random(1), 10).toArray(), DoubleStreamEx.of(new Random(1)).limit(10)
+ .toArray(), 0.0);
+ assertTrue(DoubleStreamEx.of(new Random(), 100, 1, 10).allMatch(x -> x >= 1 && x < 10));
+ assertArrayEquals(DoubleStreamEx.of(new Random(1), 100, 1, 10).toArray(), DoubleStreamEx.of(new Random(1), 1,
+ 10).limit(100).toArray(), 0.0);
+
+ DoubleStream stream = DoubleStreamEx.of(1, 2, 3);
+ assertSame(stream, DoubleStreamEx.of(stream));
+
+ assertArrayEquals(new double[] { 1, 5, 3 }, DoubleStreamEx.of(
+ Spliterators.spliterator(new double[] { 1, 5, 3 }, 0)).toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, 5, 3 }, DoubleStreamEx.of(
+ Spliterators.iterator(Spliterators.spliterator(new double[] { 1, 5, 3 }, 0))).toArray(), 0.0);
+ assertArrayEquals(new double[0], DoubleStreamEx
+ .of(Spliterators.iterator(Spliterators.emptyDoubleSpliterator())).parallel().toArray(), 0.0);
+
+ assertArrayEquals(new double[] { 2, 4, 6 }, DoubleStreamEx.of(new Double[] { 2.0, 4.0, 6.0 }).toArray(), 0.0);
+ }
+
+ @Test
+ public void testOfDoubleBuffer() {
+ double[] data = LongStreamEx.range(100).asDoubleStream().toArray();
+ assertArrayEquals(data, DoubleStreamEx.of(DoubleBuffer.wrap(data)).toArray(), 0.0);
+ assertArrayEquals(LongStreamEx.range(50, 70).asDoubleStream().toArray(), DoubleStreamEx.of(DoubleBuffer.wrap(
+ data, 50, 20)).toArray(), 0.0);
+ assertArrayEquals(data, DoubleStreamEx.of(DoubleBuffer.wrap(data)).parallel().toArray(), 0.0);
+ assertArrayEquals(LongStreamEx.range(50, 70).asDoubleStream().toArray(), DoubleStreamEx.of(DoubleBuffer.wrap(
+ data, 50, 20)).parallel().toArray(), 0.0);
+ }
+
+ @Test
+ public void testIterate() {
+ assertArrayEquals(new double[] { 1, 2, 4, 8, 16 }, DoubleStreamEx.iterate(1, x -> x * 2).limit(5).toArray(),
+ 0.0);
+ assertArrayEquals(new double[] { 1, 2, 4, 8, 16, 32, 64 }, DoubleStreamEx.iterate(1, x -> x < 100, x -> x * 2)
+ .toArray(), 0.0);
+ assertEquals(0, DoubleStreamEx.iterate(0, x -> x < 0, x -> 1 / x).count());
+ assertFalse(DoubleStreamEx.iterate(1, x -> x < 100, x -> x * 2).findFirst(x -> x == 10).isPresent());
+ checkSpliterator("iterate", () -> DoubleStreamEx.iterate(1, x -> x < 100, x -> x * 2).spliterator());
+ }
+
+ @Test
+ public void testBasics() {
+ assertFalse(DoubleStreamEx.of(1).isParallel());
+ assertTrue(DoubleStreamEx.of(1).parallel().isParallel());
+ assertFalse(DoubleStreamEx.of(1).parallel().sequential().isParallel());
+ AtomicInteger i = new AtomicInteger();
+ try (DoubleStreamEx s = DoubleStreamEx.of(1).onClose(i::incrementAndGet)) {
+ assertEquals(1, s.count());
+ }
+ assertEquals(1, i.get());
+ assertEquals(6, IntStreamEx.range(0, 4).asDoubleStream().sum(), 0);
+ assertEquals(3, IntStreamEx.range(0, 4).asDoubleStream().max().getAsDouble(), 0);
+ assertEquals(0, IntStreamEx.range(0, 4).asDoubleStream().min().getAsDouble(), 0);
+ assertEquals(1.5, IntStreamEx.range(0, 4).asDoubleStream().average().getAsDouble(), 0.000001);
+ assertEquals(4, IntStreamEx.range(0, 4).asDoubleStream().summaryStatistics().getCount());
+ assertArrayEquals(new double[] { 1, 2, 3 },
+ IntStreamEx.range(0, 5).asDoubleStream().skip(1).limit(3).toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(3, 1, 2).sorted().toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(1, 2, 1, 3, 2).distinct().toArray(), 0.0);
+ assertArrayEquals(new int[] { 2, 4, 6 }, IntStreamEx.range(1, 4).asDoubleStream().mapToInt(x -> (int) x * 2)
+ .toArray());
+ assertArrayEquals(new long[] { 2, 4, 6 }, IntStreamEx.range(1, 4).asDoubleStream().mapToLong(x -> (long) x * 2)
+ .toArray());
+ assertArrayEquals(new double[] { 2, 4, 6 }, IntStreamEx.range(1, 4).asDoubleStream().map(x -> x * 2).toArray(),
+ 0.0);
+ assertArrayEquals(new double[] { 1, 3 }, IntStreamEx.range(0, 5).asDoubleStream().filter(x -> x % 2 == 1)
+ .toArray(), 0.0);
+ assertEquals(6.0, DoubleStreamEx.of(1.0, 2.0, 3.0).reduce(Double::sum).getAsDouble(), 0.0);
+ assertEquals(Long.MAX_VALUE, LongStreamEx.rangeClosed(1, Long.MAX_VALUE).asDoubleStream().spliterator()
+ .getExactSizeIfKnown());
+
+ assertArrayEquals(new double[] { 4, 2, 0, -2, -4 }, DoubleStreamEx.zip(new double[] { 5, 4, 3, 2, 1 },
+ new double[] { 1, 2, 3, 4, 5 }, (a, b) -> a - b).toArray(), 0.0);
+ assertEquals("1.0; 0.5; 0.25; 0.125", DoubleStreamEx.of(1.0, 0.5, 0.25, 0.125).mapToObj(String::valueOf)
+ .joining("; "));
+ List list = new ArrayList<>();
+ DoubleStreamEx.of(1.0, 0.5, 0.25, 0.125).forEach(list::add);
+ assertEquals(Arrays.asList(1.0, 0.5, 0.25, 0.125), list);
+ list = new ArrayList<>();
+ DoubleStreamEx.of(1.0, 0.5, 0.25, 0.125).parallel().forEachOrdered(list::add);
+ assertEquals(Arrays.asList(1.0, 0.5, 0.25, 0.125), list);
+
+ assertFalse(DoubleStreamEx.of(1.0, 2.0, 2.5).anyMatch(x -> x < 0.0));
+ assertTrue(DoubleStreamEx.of(1.0, 2.0, 2.5).anyMatch(x -> x >= 2.5));
+ assertTrue(DoubleStreamEx.of(1.0, 2.0, 2.5).noneMatch(x -> x < 0.0));
+ assertFalse(DoubleStreamEx.of(1.0, 2.0, 2.5).noneMatch(x -> x >= 2.5));
+ assertEquals(5.0, DoubleStreamEx.of(1.0, 2.0, 2.5).reduce(1, (a, b) -> a * b), 0.0);
+
+ assertTrue(DoubleStreamEx.of(1, 2, 3).spliterator().hasCharacteristics(Spliterator.ORDERED));
+ assertFalse(DoubleStreamEx.of(1, 2, 3).unordered().spliterator().hasCharacteristics(Spliterator.ORDERED));
+
+ OfDouble iterator = DoubleStreamEx.of(1.0, 2.0, 3.0).iterator();
+ assertEquals(1.0, iterator.next(), 0.0);
+ assertEquals(2.0, iterator.next(), 0.0);
+ assertEquals(3.0, iterator.next(), 0.0);
+ assertFalse(iterator.hasNext());
+ }
+
+ @Test
+ public void testForEach() {
+ streamEx(() -> StreamEx.of(1, 2, 3), s -> {
+ AtomicInteger count = new AtomicInteger(0);
+ s.get().mapToDouble(Integer::intValue).forEach(v -> count.addAndGet((int) v));
+ assertEquals(6, count.get());
+ s.get().mapToDouble(Integer::intValue).pairMap((a, b) -> b - a).forEach(v -> count.addAndGet((int) v));
+ assertEquals(8, count.get());
+ });
+ }
+
+ @Test
+ public void testFlatMap() {
+ assertArrayEquals(new int[] { 1, 5, 2, 3, 3, 2, 0, 9 }, DoubleStreamEx.of(1.5, 2.3, 3.2, 0.9).flatMapToInt(
+ x -> IntStreamEx.of((int) Math.floor(x), (int) (Math.round(10 * (x - Math.floor(x)))))).toArray());
+ assertEquals("1:.:5:2:2:.:3:3:.:2:0:.:9", DoubleStreamEx.of(1.5, 22.3, 3.2, 0.9).flatMapToObj(
+ x -> StreamEx.split(String.valueOf(x), "")).joining(":"));
+
+ assertArrayEquals(new double[] { 0.0, 0.0, 1.0, 0.0, 1.0, 2.0 }, DoubleStreamEx.of(1, 2, 3).flatMap(
+ x -> IntStreamEx.range((int) x).asDoubleStream()).toArray(), 0.0);
+
+ assertArrayEquals(new long[] { 0x3FF0000000000000L, 0x3FF0000000000000L, 0x4000000000000000L,
+ 0x4000000000000000L, 0x7FF8000000000000L, 0x7FF8000000000000L }, DoubleStreamEx.of(1, 2, Double.NaN)
+ .flatMapToLong(x -> LongStream.of(Double.doubleToLongBits(x), Double.doubleToRawLongBits(x))).toArray());
+ }
+
+ @Test
+ public void testPrepend() {
+ assertArrayEquals(new double[] { -1, 0, 1, 2, 3 }, DoubleStreamEx.of(1, 2, 3).prepend(-1, 0).toArray(), 0.0);
+ assertArrayEquals(new double[] { -1, 0, 1, 2, 3 }, DoubleStreamEx.of(1, 2, 3).prepend(DoubleStream.of(-1, 0))
+ .toArray(), 0.0);
+ DoubleStreamEx s = DoubleStreamEx.of(1, 2, 3);
+ assertSame(s, s.prepend());
+ }
+
+ @Test
+ public void testAppend() {
+ assertArrayEquals(new double[] { 1, 2, 3, 4, 5 }, DoubleStreamEx.of(1, 2, 3).append(4, 5).toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, 2, 3, 4, 5 }, DoubleStreamEx.of(1, 2, 3).append(DoubleStream.of(4, 5))
+ .toArray(), 0.0);
+ DoubleStreamEx s = DoubleStreamEx.of(1, 2, 3);
+ assertSame(s, s.append());
+ }
+
+ @Test
+ public void testRanges() {
+ assertArrayEquals(new double[] { 5, 4, Double.POSITIVE_INFINITY }, DoubleStreamEx.of(1, 5, 3, 4, -1,
+ Double.POSITIVE_INFINITY).greater(3).toArray(), 0.0);
+ assertArrayEquals(new double[] {}, DoubleStreamEx.of(1, 5, 3, 4, -1, Double.POSITIVE_INFINITY).greater(
+ Double.POSITIVE_INFINITY).toArray(), 0.0);
+ assertArrayEquals(new double[] { 5, 3, 4, Double.POSITIVE_INFINITY }, DoubleStreamEx.of(1, 5, 3, 4, -1,
+ Double.POSITIVE_INFINITY).atLeast(3).toArray(), 0.0);
+ assertArrayEquals(new double[] { Double.POSITIVE_INFINITY }, DoubleStreamEx.of(1, 5, 3, 4, -1,
+ Double.POSITIVE_INFINITY).atLeast(Double.POSITIVE_INFINITY).toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, -1 }, DoubleStreamEx.of(1, 5, 3, 4, -1, Double.POSITIVE_INFINITY).less(3)
+ .toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, 3, -1 }, DoubleStreamEx.of(1, 5, 3, 4, -1, Double.POSITIVE_INFINITY)
+ .atMost(3).toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, 3, 4, -1 }, DoubleStreamEx.of(1, 5, 3, 4, -1, Double.POSITIVE_INFINITY)
+ .atMost(4).toArray(), 0.0);
+ }
+
+ @Test
+ public void testFind() {
+ assertEquals(6.0, LongStreamEx.range(1, 10).asDoubleStream().findFirst(i -> i > 5).getAsDouble(), 0.0);
+ assertFalse(LongStreamEx.range(1, 10).asDoubleStream().findAny(i -> i > 10).isPresent());
+ }
+
+ @Test
+ public void testRemove() {
+ assertArrayEquals(new double[] { 1, 2 }, DoubleStreamEx.of(1, 2, 3).remove(x -> x > 2).toArray(), 0.0);
+ }
+
+ @Test
+ public void testSort() {
+ assertArrayEquals(new double[] { 3, 2, 1 }, DoubleStreamEx.of(1, 2, 3).sortedByDouble(x -> -x).toArray(), 0.0);
+ assertArrayEquals(new double[] { Double.NaN, Double.NaN, Double.POSITIVE_INFINITY, Double.MAX_VALUE, 1000, 1,
+ Double.MIN_VALUE, 0, -0.0, -Double.MIN_VALUE * 3, -10, -Double.MAX_VALUE / 1.1, -Double.MAX_VALUE,
+ Double.NEGATIVE_INFINITY }, DoubleStreamEx.of(0, 1, -Double.MIN_VALUE * 3, 1000, -10,
+ -Double.MAX_VALUE, Double.POSITIVE_INFINITY, Double.NaN, Double.NEGATIVE_INFINITY, Double.NaN,
+ Double.MAX_VALUE, -0.0, Double.MIN_VALUE, -Double.MAX_VALUE / 1.1).reverseSorted().toArray(), 0.0);
+ assertArrayEquals(new double[] { 1, 10, 2, 21, 9 }, DoubleStreamEx.of(1, 10, 2, 9, 21)
+ .sortedBy(String::valueOf).toArray(), 0.0);
+
+ assertArrayEquals(new double[] { 0.4, 1.5, 1.3, 2.3, 2.1, 2.0, 3.7 }, DoubleStreamEx.of(1.5, 2.3, 1.3, 2.1,
+ 3.7, 0.4, 2.0).sortedByInt(x -> (int) x).toArray(), 0.0);
+
+ assertArrayEquals(new double[] { 0.4, 1.5, 1.3, 2.3, 2.1, 2.0, 3.7 }, DoubleStreamEx.of(1.5, 2.3, 1.3, 2.1,
+ 3.7, 0.4, 2.0).sortedByLong(x -> (long) x).toArray(), 0.0);
+ double nonCanonicalNan = Double.longBitsToDouble(0xfff8000000000001L);
+ double nonCanonicalNan2 = Double.longBitsToDouble(0x7ff8000000000000L);
+ assertTrue(Double.isNaN(nonCanonicalNan));
+ assertTrue(Double.isNaN(nonCanonicalNan2));
+ double[] data = {Double.NEGATIVE_INFINITY, 0.0, 1.0, Double.POSITIVE_INFINITY, Double.NaN, nonCanonicalNan,
+ nonCanonicalNan2};
+ double[] reverseData = {nonCanonicalNan, nonCanonicalNan2, Double.NaN, Double.POSITIVE_INFINITY, 1.0, 0.0,
+ Double.NEGATIVE_INFINITY};
+ assertArrayEquals(DoubleStreamEx.of(data).mapToLong(Double::doubleToRawLongBits).toArray(),
+ DoubleStreamEx.of(data).sorted().mapToLong(Double::doubleToRawLongBits).toArray());
+ assertArrayEquals(DoubleStreamEx.of(reverseData).mapToLong(Double::doubleToRawLongBits).toArray(),
+ DoubleStreamEx.of(data).reverseSorted().mapToLong(Double::doubleToRawLongBits).toArray());
+ }
+
+ @SafeVarargs
+ private static void checkEmpty(Function... fns) {
+ int i = 0;
+ for (Function fn : fns) {
+ assertFalse("#" + i, fn.apply(DoubleStreamEx.empty()).isPresent());
+ assertFalse("#" + i, fn.apply(DoubleStreamEx.of(1, 2, 3, 4).greater(5).parallel()).isPresent());
+ assertEquals("#" + i, 10, fn.apply(DoubleStreamEx.of(1, 1, 1, 1, 10, 10, 10, 10).greater(5).parallel())
+ .getAsDouble(), 0.0);
+ i++;
+ }
+ }
+
+ @Test
+ public void testMinMax() {
+ checkEmpty(s -> s.maxBy(Double::valueOf), s -> s.maxByInt(x -> (int) x), s -> s.maxByLong(x -> (long) x),
+ s -> s.maxByDouble(x -> x), s -> s.minBy(Double::valueOf), s -> s.minByInt(x -> (int) x), s -> s
+ .minByLong(x -> (long) x), s -> s.minByDouble(x -> x));
+ assertEquals(9, IntStreamEx.range(5, 12).asDoubleStream().max(
+ Comparator.comparing(String::valueOf)).getAsDouble(), 0.0);
+ assertEquals(10, IntStreamEx.range(5, 12).asDoubleStream().min(
+ Comparator.comparing(String::valueOf)).getAsDouble(), 0.0);
+ assertEquals(9, IntStreamEx.range(5, 12).asDoubleStream().maxBy(String::valueOf).getAsDouble(), 0.0);
+ assertEquals(10, IntStreamEx.range(5, 12).asDoubleStream().minBy(String::valueOf).getAsDouble(), 0.0);
+ assertEquals(5, IntStreamEx.range(5, 12).asDoubleStream().maxByDouble(x -> 1.0 / x).getAsDouble(), 0.0);
+ assertEquals(11, IntStreamEx.range(5, 12).asDoubleStream().minByDouble(x -> 1.0 / x).getAsDouble(), 0.0);
+ assertEquals(29.0, DoubleStreamEx.of(15, 8, 31, 47, 19, 29).maxByInt(x -> (int) (x % 10 * 10 + x / 10))
+ .getAsDouble(), 0.0);
+ assertEquals(31.0, DoubleStreamEx.of(15, 8, 31, 47, 19, 29).minByInt(x -> (int) (x % 10 * 10 + x / 10))
+ .getAsDouble(), 0.0);
+ assertEquals(29.0, DoubleStreamEx.of(15, 8, 31, 47, 19, 29).maxByLong(x -> (long) (x % 10 * 10 + x / 10))
+ .getAsDouble(), 0.0);
+ assertEquals(31.0, DoubleStreamEx.of(15, 8, 31, 47, 19, 29).minByLong(x -> (long) (x % 10 * 10 + x / 10))
+ .getAsDouble(), 0.0);
+
+ Supplier s = () -> DoubleStreamEx.of(1, 50, 120, 35, 130, 12, 0);
+ DoubleToIntFunction intKey = x -> String.valueOf(x).length();
+ DoubleToLongFunction longKey = x -> String.valueOf(x).length();
+ DoubleUnaryOperator doubleKey = x -> String.valueOf(x).length();
+ DoubleFunction objKey = x -> String.valueOf(x).length();
+ List> minFns = Arrays.asList(is -> is.minByInt(intKey), is -> is
+ .minByLong(longKey), is -> is.minByDouble(doubleKey), is -> is.minBy(objKey));
+ List> maxFns = Arrays.asList(is -> is.maxByInt(intKey), is -> is
+ .maxByLong(longKey), is -> is.maxByDouble(doubleKey), is -> is.maxBy(objKey));
+ minFns.forEach(fn -> assertEquals(1, fn.apply(s.get()).getAsDouble(), 0.0));
+ minFns.forEach(fn -> assertEquals(1, fn.apply(s.get().parallel()).getAsDouble(), 0.0));
+ maxFns.forEach(fn -> assertEquals(120, fn.apply(s.get()).getAsDouble(), 0.0));
+ maxFns.forEach(fn -> assertEquals(120, fn.apply(s.get().parallel()).getAsDouble(), 0.0));
+ }
+
+ @Test
+ public void testPairMap() {
+ assertEquals(0, DoubleStreamEx.of().pairMap(Double::sum).count());
+ assertEquals(0, DoubleStreamEx.of(1.0).pairMap(Double::sum).count());
+ int[] data = new Random(1).ints(1000, 1, 1000).toArray();
+ double[] expected = new double[data.length - 1];
+ for (int i = 0; i < expected.length; i++)
+ expected[i] = (data[i + 1] - data[i]) * 1.23;
+ double[] result = IntStreamEx.of(data).parallel().asDoubleStream().pairMap((a, b) -> (b - a) * 1.23).toArray();
+ assertArrayEquals(expected, result, 0.0);
+ result = IntStreamEx.of(data).asDoubleStream().pairMap((a, b) -> (b - a) * 1.23).toArray();
+ assertArrayEquals(expected, result, 0.0);
+ assertEquals(984.0, IntStreamEx.of(data).asDoubleStream().parallel().pairMap((a, b) -> Math.abs(a - b)).max()
+ .getAsDouble(), 0.0);
+ assertArrayEquals(new double[] { 1.0, 1.0 }, DoubleStreamEx.of(1.0, 2.0, 3.0).append().parallel().pairMap(
+ (a, b) -> b - a).toArray(), 0.0);
+
+ assertArrayEquals(LongStreamEx.range(1, 100).asDoubleStream().toArray(), LongStreamEx.range(100).map(
+ i -> i * (i + 1) / 2).append(LongStream.empty()).asDoubleStream().parallel().pairMap((a, b) -> b - a)
+ .toArray(), 0.0);
+ assertArrayEquals(LongStreamEx.range(1, 100).asDoubleStream().toArray(), LongStreamEx.range(100).map(
+ i -> i * (i + 1) / 2).prepend(LongStream.empty()).asDoubleStream().parallel().pairMap((a, b) -> b - a)
+ .toArray(), 0.0);
+
+ assertEquals(1, LongStreamEx.range(1000).mapToDouble(x -> x * x).pairMap((a, b) -> b - a).pairMap(
+ (a, b) -> b - a).distinct().count());
+
+ assertFalse(LongStreamEx.range(1000).asDoubleStream().greater(2000).parallel().pairMap((a, b) -> a).findFirst()
+ .isPresent());
+ }
+
+ @Test
+ public void testToFloatArray() {
+ float[] expected = new float[10000];
+ for (int i = 0; i < expected.length; i++)
+ expected[i] = i;
+ assertArrayEquals(expected, IntStreamEx.range(0, 10000).asDoubleStream().toFloatArray(), 0.0f);
+ assertArrayEquals(expected, IntStreamEx.range(0, 10000).asDoubleStream().parallel().toFloatArray(), 0.0f);
+ assertArrayEquals(expected, IntStreamEx.range(0, 10000).asDoubleStream().greater(-1).toFloatArray(), 0.0f);
+ assertArrayEquals(expected, IntStreamEx.range(0, 10000).asDoubleStream().parallel().greater(-1).toFloatArray(),
+ 0.0f);
+ // Test when resize of internal buffer is not required on addAll (buffer size = 128)
+ assertArrayEquals(Arrays.copyOf(expected, 100),
+ IntStreamEx.range(0, 100).asDoubleStream().parallel().toFloatArray(), 0.0f);
+ }
+
+ @Test
+ public void testJoining() {
+ assertEquals("0.4,5.0,3.6,4.8", DoubleStreamEx.of(0.4, 5.0, 3.6, 4.8).joining(","));
+ assertEquals("0.4,5.0,3.6,4.8", DoubleStreamEx.of(0.4, 5.0, 3.6, 4.8).parallel().joining(","));
+ assertEquals("[0.4,5.0,3.6,4.8]", DoubleStreamEx.of(0.4, 5.0, 3.6, 4.8).joining(",", "[", "]"));
+ assertEquals("[0.4,5.0,3.6,4.8]", DoubleStreamEx.of(0.4, 5.0, 3.6, 4.8).parallel().joining(",", "[", "]"));
+ }
+
+ @Test
+ public void testMapToEntry() {
+ Map> map = DoubleStreamEx.of(0.3, 0.5, 1.3, 0.7, 1.9, 2.1).mapToEntry(x -> (int) x,
+ x -> x).grouping();
+ assertEquals(Arrays.asList(0.3, 0.5, 0.7), map.get(0));
+ assertEquals(Arrays.asList(1.3, 1.9), map.get(1));
+ assertEquals(Arrays.asList(2.1), map.get(2));
+ }
+
+ @Test
+ public void testTakeWhile() {
+ assertArrayEquals(LongStreamEx.range(100).asDoubleStream().toArray(), DoubleStreamEx.iterate(0, i -> i + 1)
+ .takeWhile(i -> i < 100).toArray(), 0.0);
+ assertEquals(0, DoubleStreamEx.iterate(0, i -> i + 1).takeWhile(i -> i < 0).count());
+ assertEquals(1, DoubleStreamEx.of(1, 3, 2).takeWhile(i -> i < 3).count());
+ assertEquals(3, DoubleStreamEx.of(1, 2, 3).takeWhile(i -> i < 100).count());
+ }
+
+ @Test
+ public void testTakeWhileInclusive() {
+ assertArrayEquals(LongStreamEx.range(101).asDoubleStream().toArray(), DoubleStreamEx.iterate(0, i -> i + 1)
+ .takeWhileInclusive(i -> i < 100).toArray(), 0.0);
+ assertEquals(1, DoubleStreamEx.iterate(0, i -> i + 1).takeWhileInclusive(i -> i < 0).count());
+ assertEquals(2, DoubleStreamEx.of(1, 3, 2).takeWhileInclusive(i -> i < 3).count());
+ assertEquals(3, DoubleStreamEx.of(1, 2, 3).takeWhileInclusive(i -> i < 100).count());
+ }
+
+ @Test
+ public void testDropWhile() {
+ assertArrayEquals(new double[] { 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }, LongStreamEx.range(100).asDoubleStream()
+ .dropWhile(i -> i % 10 < 5).limit(10).toArray(), 0.0);
+ assertEquals(100, LongStreamEx.range(100).asDoubleStream().sorted().dropWhile(i -> i % 10 < 0).count());
+ assertEquals(0, LongStreamEx.range(100).asDoubleStream().dropWhile(i -> i % 10 < 10).count());
+ assertEquals(OptionalDouble.of(0), LongStreamEx.range(100).asDoubleStream().dropWhile(i -> i % 10 < 0).findFirst());
+ assertEquals(OptionalDouble.empty(), LongStreamEx.range(100).asDoubleStream().dropWhile(i -> i % 10 < 10).findFirst());
+
+ java.util.Spliterator.OfDouble spltr = LongStreamEx.range(100).asDoubleStream().dropWhile(i -> i % 10 < 1).spliterator();
+ assertTrue(spltr.tryAdvance((double x) -> assertEquals(1, x, 0.0)));
+ Builder builder = DoubleStream.builder();
+ spltr.forEachRemaining(builder);
+ assertArrayEquals(LongStreamEx.range(2, 100).asDoubleStream().toArray(), builder.build().toArray(), 0.0);
+ }
+
+ @Test
+ public void testIndexOf() {
+ assertEquals(11, LongStreamEx.range(50, 100).asDoubleStream().indexOf(x -> x > 60).getAsLong());
+ assertFalse(LongStreamEx.range(50, 100).asDoubleStream().indexOf(x -> x < 0).isPresent());
+ assertEquals(11, LongStreamEx.range(50, 100).asDoubleStream().parallel().indexOf(x -> x > 60).getAsLong());
+ assertFalse(LongStreamEx.range(50, 100).asDoubleStream().parallel().indexOf(x -> x < 0).isPresent());
+ }
+
+ @Test
+ public void testFoldLeft() {
+ // non-associative
+ DoubleBinaryOperator accumulator = (x, y) -> (x + y) * (x + y);
+ assertEquals(2322576, DoubleStreamEx.constant(3, 4).foldLeft(accumulator).orElse(-1), 0.0);
+ assertEquals(2322576, DoubleStreamEx.constant(3, 4).parallel().foldLeft(accumulator).orElse(-1), 0.0);
+ assertFalse(DoubleStreamEx.empty().foldLeft(accumulator).isPresent());
+ assertEquals(144, DoubleStreamEx.of(1, 2, 3).foldLeft(0.0, accumulator), 144);
+ assertEquals(144, DoubleStreamEx.of(1, 2, 3).parallel().foldLeft(0.0, accumulator), 144);
+ }
+
+ @Test
+ public void testMapFirstLast() {
+ assertArrayEquals(new double[] { -1, 2, 3, 4, 7 }, DoubleStreamEx.of(1, 2, 3, 4, 5).mapFirst(x -> x - 2.0)
+ .mapLast(x -> x + 2.0).toArray(), 0.0);
+ }
+
+ @Test
+ public void testPeekFirst() {
+ double[] input = {1, 10, 100, 1000};
+
+ AtomicReference firstElement = new AtomicReference<>();
+ assertArrayEquals(new double[] {10, 100, 1000}, DoubleStreamEx.of(input).peekFirst(firstElement::set).skip(1).toArray(), 0.0);
+ assertEquals(1, firstElement.get(), 0.0);
+
+ assertArrayEquals(new double[] {10, 100, 1000}, DoubleStreamEx.of(input).skip(1).peekFirst(firstElement::set).toArray(), 0.0);
+ assertEquals(10, firstElement.get(), 0.0);
+
+ firstElement.set(-1.0);
+ assertArrayEquals(new double[] {}, DoubleStreamEx.of(input).skip(4).peekFirst(firstElement::set).toArray(), 0.0);
+ assertEquals(-1, firstElement.get(), 0.0);
+ }
+
+ @Test
+ public void testPeekLast() {
+ double[] input = {1, 10, 100, 1000};
+ AtomicReference lastElement = new AtomicReference<>();
+ assertArrayEquals(new double[] {1, 10, 100}, DoubleStreamEx.of(input).peekLast(lastElement::set).limit(3).toArray(), 0.0);
+ assertNull(lastElement.get());
+
+ assertArrayEquals(new double[] { 1, 10, 100 }, DoubleStreamEx.of(input).less(1000).peekLast(lastElement::set)
+ .limit(3).toArray(), 0.0);
+ assertEquals(100, lastElement.get(), 0.0);
+
+ assertArrayEquals(input, DoubleStreamEx.of(input).peekLast(lastElement::set).limit(4).toArray(), 0.0);
+ assertEquals(1000, lastElement.get(), 0.0);
+
+ assertArrayEquals(new double[] {1, 10, 100}, DoubleStreamEx.of(input).limit(3).peekLast(lastElement::set).toArray(), 0.0);
+ assertEquals(100, lastElement.get(), 0.0);
+ }
+
+ @Test
+ public void testScanLeft() {
+ assertArrayEquals(new double[] { 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 }, LongStreamEx.range(10).asDoubleStream()
+ .scanLeft(Double::sum), 0.0);
+ assertArrayEquals(new double[] { 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 }, LongStreamEx.range(10).asDoubleStream()
+ .parallel().scanLeft(Double::sum), 0.0);
+ assertArrayEquals(new double[] { 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 }, LongStreamEx.range(10).asDoubleStream()
+ .filter(x -> true).scanLeft(Double::sum), 0.0);
+ assertArrayEquals(new double[] { 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 }, LongStreamEx.range(10).asDoubleStream()
+ .filter(x -> true).parallel().scanLeft(Double::sum), 0.0);
+ assertArrayEquals(new double[] { 1, 1, 2, 6, 24, 120 }, LongStreamEx.rangeClosed(1, 5).asDoubleStream()
+ .scanLeft(1, (a, b) -> a * b), 0.0);
+ assertArrayEquals(new double[] { 1, 1, 2, 6, 24, 120 }, LongStreamEx.rangeClosed(1, 5).asDoubleStream()
+ .parallel().scanLeft(1, (a, b) -> a * b), 0.0);
+ }
+
+ // Reads numbers from scanner stopping when non-number is encountered
+ // leaving scanner in known state
+ private static DoubleStreamEx scannerDoubles(Scanner sc) {
+ return DoubleStreamEx.produce(action -> {
+ if (sc.hasNextDouble())
+ action.accept(sc.nextDouble());
+ return sc.hasNextDouble();
+ });
+ }
+
+ @Test
+ public void testProduce() {
+ Scanner sc = new Scanner("1.0 2.5 3 -4.6 test");
+ sc.useLocale(Locale.ENGLISH);
+ assertArrayEquals(new double[] {1, 2.5, 3, -4.6}, scannerDoubles(sc).toArray(), 0.0);
+ assertEquals("test", sc.next());
+ }
+
+ @Test
+ public void testPrefix() {
+ assertArrayEquals(new double[] { 1, 3, 6, 10, 20 }, DoubleStreamEx.of(1, 2, 3, 4, 10).prefix(Double::sum).toArray(), 0.0);
+ assertEquals(OptionalDouble.of(10), DoubleStreamEx.of(1, 2, 3, 4, 10).prefix(Double::sum).findFirst(x -> x > 7));
+ assertEquals(OptionalDouble.empty(), DoubleStreamEx.of(1, 2, 3, 4, 10).prefix(Double::sum).findFirst(x -> x > 20));
+ }
+
+ @Test
+ public void testIntersperse() {
+ assertArrayEquals(new double[] { 1, 0, 10, 0, 100, 0, 1000 }, DoubleStreamEx.of(1, 10, 100, 1000).intersperse(0)
+ .toArray(), 0.0);
+ assertEquals(0L, IntStreamEx.empty().intersperse(1).count());
+ }
+}
diff --git a/src/test/java/one/util/streamex/EmitterTest.java b/src/test/java/one/util/streamex/api/EmitterTest.java
similarity index 85%
rename from src/test/java/one/util/streamex/EmitterTest.java
rename to src/test/java/one/util/streamex/api/EmitterTest.java
index fc37aa1e..7f33dbb9 100644
--- a/src/test/java/one/util/streamex/EmitterTest.java
+++ b/src/test/java/one/util/streamex/api/EmitterTest.java
@@ -1,181 +1,191 @@
-/*
- * Copyright 2015, 2019 StreamEx contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package one.util.streamex;
-
-import java.math.BigInteger;
-import java.util.Iterator;
-import java.util.function.BinaryOperator;
-import java.util.function.LongPredicate;
-import java.util.function.Predicate;
-import java.util.function.UnaryOperator;
-
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-
-import one.util.streamex.DoubleStreamEx.DoubleEmitter;
-import one.util.streamex.IntStreamEx.IntEmitter;
-import one.util.streamex.LongStreamEx.LongEmitter;
-import one.util.streamex.StreamEx.Emitter;
-
-import static java.util.Arrays.asList;
-import static one.util.streamex.TestHelpers.checkSpliterator;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-/**
- * @author Tagir Valeev
- */
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class EmitterTest {
- // Like Java-9 Stream.iterate(seed, test, op)
- public static Emitter iterate(T seed, Predicate super T> test, UnaryOperator op) {
- return test.test(seed) ? action -> {
- action.accept(seed);
- return iterate(op.apply(seed), test, op);
- } : null;
- }
-
- // Collatz sequence starting from given number
- public static Emitter collatz(int start) {
- return action -> {
- action.accept(start);
- return start == 1 ? null : collatz(start % 2 == 0 ? start / 2 : start * 3 + 1);
- };
- }
-
- public static IntEmitter collatzInt(int start) {
- return action -> {
- action.accept(start);
- return start == 1 ? null : collatzInt(start % 2 == 0 ? start / 2 : start * 3 + 1);
- };
- }
-
- public static LongEmitter collatzLong(long start) {
- return action -> {
- action.accept(start);
- return start == 1 ? null : collatzLong(start % 2 == 0 ? start / 2 : start * 3 + 1);
- };
- }
-
- // Stream of Fibonacci numbers
- public static StreamEx fibonacci() {
- return fibonacci(BigInteger.ONE, BigInteger.ZERO).stream();
- }
-
- private static Emitter fibonacci(BigInteger first, BigInteger second) {
- return action -> {
- BigInteger next = first.add(second);
- action.accept(next);
- return fibonacci(second, next);
- };
- }
-
- // Perform scanLeft on the iterator
- public static Emitter scanLeft(Iterator iter, T initial, BinaryOperator reducer) {
- return action -> {
- if (!iter.hasNext())
- return null;
- T sum = reducer.apply(initial, iter.next());
- action.accept(sum);
- return scanLeft(iter, sum, reducer);
- };
- }
-
- public static Emitter flatTest(int start) {
- return action -> {
- for (int i = 0; i < start; i++)
- action.accept(start);
- return start == 0 ? null : flatTest(start - 1);
- };
- }
-
- public static IntEmitter flatTestInt(int start) {
- return action -> {
- for (int i = 0; i < start; i++)
- action.accept(start);
- return start == 0 ? null : flatTestInt(start - 1);
- };
- }
-
- public static LongEmitter flatTestLong(int start) {
- return action -> {
- for (int i = 0; i < start; i++)
- action.accept(start);
- return start == 0 ? null : flatTestLong(start - 1);
- };
- }
-
- public static DoubleEmitter flatTestDouble(int start) {
- return action -> {
- for (int i = 0; i < start; i++)
- action.accept(start);
- return start == 0 ? null : flatTestDouble(start - 1);
- };
- }
-
- public static LongStreamEx primes() {
- return ((LongEmitter) (action -> {
- action.accept(2);
- return primes(3, x -> x % 2 != 0);
- })).stream();
- }
-
- 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));
- };
- }
-
- @Test
- public void testEmitter() {
- assertEquals(asList(17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1), collatz(17).stream().toList());
- checkSpliterator("collatz", asList(17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1), collatz(17)::spliterator);
- assertArrayEquals(new int[] {17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1}, collatzInt(17).stream().toArray());
- checkSpliterator("collatzInt", asList(17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1), collatzInt(17)::spliterator);
- assertArrayEquals(new long[] {17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1}, collatzLong(17).stream().toArray());
- checkSpliterator("collatzLong", asList(17L, 52L, 26L, 13L, 40L, 20L, 10L, 5L, 16L, 8L, 4L, 2L, 1L),
- collatzLong(17)::spliterator);
- assertTrue(collatz(17).stream().has(1));
- assertTrue(collatzInt(17).stream().has(1));
- assertFalse(collatzLong(17).stream().has(0));
- assertEquals(asList(1, 2, 3, 4, 5, 6, 7, 8, 9), iterate(1, x -> x < 10, x -> x + 1).stream().toList());
-
- // Extracting to variables is necessary to work-around javac <8u40 bug
- String expected = "354224848179261915075";
- String actual = fibonacci().skip(99).findFirst().get().toString();
- assertEquals(expected, actual);
- assertEquals(asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55), fibonacci().map(BigInteger::intValueExact).limit(10)
- .toList());
-
- assertEquals(asList("aa", "aabbb", "aabbbc"), scanLeft(asList("aa", "bbb", "c").iterator(), "", String::concat)
- .stream().toList());
-
- assertEquals(asList(4, 4, 4, 4, 3, 3, 3, 2, 2, 1), flatTest(4).stream().toList());
- assertEquals(asList(4, 4, 4, 4, 3, 3, 3, 2, 2), flatTest(4).stream().limit(9).toList());
-
- checkSpliterator("flatTest", asList(4, 4, 4, 4, 3, 3, 3, 2, 2, 1), flatTest(4)::spliterator);
- checkSpliterator("flatTest", asList(4, 4, 4, 4, 3, 3, 3, 2, 2, 1), flatTestInt(4)::spliterator);
- checkSpliterator("flatTest", asList(4L, 4L, 4L, 4L, 3L, 3L, 3L, 2L, 2L, 1L), flatTestLong(4)::spliterator);
- checkSpliterator("flatTest", asList(4.0, 4.0, 4.0, 4.0, 3.0, 3.0, 3.0, 2.0, 2.0, 1.0), flatTestDouble(4)::spliterator);
-
- assertEquals(7919L, primes().skip(999).findFirst().getAsLong());
- }
-}
+/*
+ * Copyright 2015, 2020 StreamEx contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package one.util.streamex.api;
+
+import java.math.BigInteger;
+import java.util.Iterator;
+import java.util.function.BinaryOperator;
+import java.util.function.LongPredicate;
+import java.util.function.Predicate;
+import java.util.function.UnaryOperator;
+
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runners.MethodSorters;
+
+import one.util.streamex.DoubleStreamEx.DoubleEmitter;
+import one.util.streamex.IntStreamEx.IntEmitter;
+import one.util.streamex.LongStreamEx;
+import one.util.streamex.LongStreamEx.LongEmitter;
+import one.util.streamex.StreamEx;
+import one.util.streamex.StreamEx.Emitter;
+import one.util.streamex.TestHelpers;
+
+import static java.util.Arrays.asList;
+import static one.util.streamex.TestHelpers.checkSpliterator;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * @author Tagir Valeev
+ */
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class EmitterTest {
+ // Like Java-9 Stream.iterate(seed, test, op)
+ public static Emitter iterate(T seed, Predicate super T> test, UnaryOperator op) {
+ return test.test(seed) ? action -> {
+ action.accept(seed);
+ return iterate(op.apply(seed), test, op);
+ } : null;
+ }
+
+ // Collatz sequence starting from given number
+ public static Emitter collatz(int start) {
+ return action -> {
+ action.accept(start);
+ return start == 1 ? null : collatz(start % 2 == 0 ? start / 2 : start * 3 + 1);
+ };
+ }
+
+ public static IntEmitter collatzInt(int start) {
+ return action -> {
+ action.accept(start);
+ return start == 1 ? null : collatzInt(start % 2 == 0 ? start / 2 : start * 3 + 1);
+ };
+ }
+
+ public static LongEmitter collatzLong(long start) {
+ return action -> {
+ action.accept(start);
+ return start == 1 ? null : collatzLong(start % 2 == 0 ? start / 2 : start * 3 + 1);
+ };
+ }
+
+ // Stream of Fibonacci numbers
+ public static StreamEx fibonacci() {
+ return fibonacci(BigInteger.ONE, BigInteger.ZERO).stream();
+ }
+
+ private static Emitter fibonacci(BigInteger first, BigInteger second) {
+ return action -> {
+ BigInteger next = first.add(second);
+ action.accept(next);
+ return fibonacci(second, next);
+ };
+ }
+
+ // Perform scanLeft on the iterator
+ public static Emitter scanLeft(Iterator iter, T initial, BinaryOperator reducer) {
+ return action -> {
+ if (!iter.hasNext())
+ return null;
+ T sum = reducer.apply(initial, iter.next());
+ action.accept(sum);
+ return scanLeft(iter, sum, reducer);
+ };
+ }
+
+ public static Emitter flatTest(int start) {
+ return action -> {
+ for (int i = 0; i < start; i++)
+ action.accept(start);
+ return start == 0 ? null : flatTest(start - 1);
+ };
+ }
+
+ public static IntEmitter flatTestInt(int start) {
+ return action -> {
+ for (int i = 0; i < start; i++)
+ action.accept(start);
+ return start == 0 ? null : flatTestInt(start - 1);
+ };
+ }
+
+ public static LongEmitter flatTestLong(int start) {
+ return action -> {
+ for (int i = 0; i < start; i++)
+ action.accept(start);
+ return start == 0 ? null : flatTestLong(start - 1);
+ };
+ }
+
+ public static DoubleEmitter flatTestDouble(int start) {
+ return action -> {
+ for (int i = 0; i < start; i++)
+ action.accept(start);
+ return start == 0 ? null : flatTestDouble(start - 1);
+ };
+ }
+
+ public static LongStreamEx primes() {
+ return ((LongEmitter) (action -> {
+ action.accept(2);
+ return primes(3, x -> x % 2 != 0);
+ })).stream();
+ }
+
+ 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));
+ };
+ }
+
+ @Test
+ public void testEmitter() {
+ assertEquals(asList(17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1), collatz(17).stream().toList());
+ checkSpliterator("collatz", asList(17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1), collatz(17)::spliterator);
+ assertArrayEquals(new int[] { 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 },
+ collatzInt(17).stream().toArray());
+ checkSpliterator("collatzInt", asList(17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1),
+ collatzInt(17)::spliterator);
+ assertArrayEquals(new long[] { 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 },
+ collatzLong(17).stream().toArray());
+ checkSpliterator("collatzLong", asList(17L, 52L, 26L, 13L, 40L, 20L, 10L, 5L, 16L, 8L, 4L, 2L, 1L),
+ collatzLong(17)::spliterator);
+ assertTrue(collatz(17).stream().has(1));
+ assertTrue(collatzInt(17).stream().has(1));
+ assertFalse(collatzLong(17).stream().has(0));
+ assertEquals(asList(1, 2, 3, 4, 5, 6, 7, 8, 9), iterate(1, x -> x < 10, x -> x + 1).stream().toList());
+
+ // Extracting to variables is necessary to work-around javac <8u40 bug
+ String expected = "354224848179261915075";
+ String actual = fibonacci().skip(99).findFirst().get().toString();
+ assertEquals(expected, actual);
+ assertEquals(asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55), fibonacci().map(BigInteger::intValueExact).limit(10)
+ .toList());
+
+ assertEquals(asList("aa", "aabbb", "aabbbc"), scanLeft(asList("aa", "bbb", "c").iterator(), "", String::concat)
+ .stream().toList());
+
+ assertEquals(asList(4, 4, 4, 4, 3, 3, 3, 2, 2, 1), flatTest(4).stream().toList());
+ assertEquals(asList(4, 4, 4, 4, 3, 3, 3, 2, 2), flatTest(4).stream().limit(9).toList());
+
+ TestHelpers.checkSpliterator("flatTest", asList(4, 4, 4, 4, 3, 3, 3, 2, 2, 1),
+ flatTest(4)::spliterator);
+ TestHelpers.checkSpliterator("flatTest", asList(4, 4, 4, 4, 3, 3, 3, 2, 2, 1),
+ flatTestInt(4)::spliterator);
+ TestHelpers.checkSpliterator("flatTest", asList(4L, 4L, 4L, 4L, 3L, 3L, 3L, 2L, 2L, 1L),
+ flatTestLong(4)::spliterator);
+ TestHelpers.checkSpliterator("flatTest", asList(4.0, 4.0, 4.0, 4.0, 3.0, 3.0, 3.0, 2.0, 2.0, 1.0),
+ flatTestDouble(4)::spliterator);
+
+ assertEquals(7919L, primes().skip(999).findFirst().getAsLong());
+ }
+}
diff --git a/src/test/java/one/util/streamex/EntryStreamTest.java b/src/test/java/one/util/streamex/api/EntryStreamTest.java
similarity index 98%
rename from src/test/java/one/util/streamex/EntryStreamTest.java
rename to src/test/java/one/util/streamex/api/EntryStreamTest.java
index 80e33644..0f7f2f37 100644
--- a/src/test/java/one/util/streamex/EntryStreamTest.java
+++ b/src/test/java/one/util/streamex/api/EntryStreamTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2015, 2019 StreamEx contributors
+ * Copyright 2015, 2020 StreamEx contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package one.util.streamex;
+package one.util.streamex.api;
import java.util.AbstractMap;
import java.util.AbstractMap.SimpleEntry;
@@ -47,11 +47,15 @@
import org.junit.Test;
import org.junit.runners.MethodSorters;
-import one.util.streamex.StreamExTest.Point;
+import one.util.streamex.EntryStream;
+import one.util.streamex.IntStreamEx;
+import one.util.streamex.MoreCollectors;
+import one.util.streamex.StreamEx;
+import one.util.streamex.TestHelpers.Point;
import static java.util.Arrays.asList;
import static one.util.streamex.TestHelpers.StreamExSupplier;
-import static one.util.streamex.TestHelpers.assertThrows;
+import static one.util.streamex.TestHelpers.checkAsString;
import static one.util.streamex.TestHelpers.checkIllegalStateException;
import static one.util.streamex.TestHelpers.entryStream;
import static one.util.streamex.TestHelpers.repeat;
@@ -63,6 +67,7 @@
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -71,10 +76,6 @@
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class EntryStreamTest {
- private static void checkAsString(String expected, EntryStream, ?> stream) {
- assertEquals(expected, stream.join("->").joining(";"));
- }
-
private static Map createMap() {
Map data = new LinkedHashMap<>();
data.put("a", 1);
@@ -85,11 +86,14 @@ private static Map createMap() {
@Test
public void testCreate() {
+ // double test is intended to caugh the bug in `EntryStream.emtpy()` related to sharing object
assertEquals(0, EntryStream.empty().count());
assertEquals(0, EntryStream.empty().count());
+
Map data = createMap();
assertEquals(data, EntryStream.of(data).toMap());
assertEquals(data, EntryStream.of(data.entrySet().stream()).toMap());
+
Map expected = new HashMap<>();
expected.put("aaa", 3);
expected.put("bbb", 3);
@@ -102,10 +106,6 @@ public void testCreate() {
assertEquals(expected, StreamEx.of(Collections.singletonMap("aaa", 3), Collections.singletonMap("bbb", 3),
Collections.singletonMap("c", 1), Collections.emptyMap()).flatMapToEntry(m -> m).toMap());
- EntryStream stream = EntryStream.of(data);
- assertSame(stream.stream(), EntryStream.of(stream).stream());
- assertSame(stream.stream(), EntryStream.of(StreamEx.of(EntryStream.of(stream))).stream());
-
assertEquals(Collections.singletonMap("aaa", 3), EntryStream.of(
Collections.singletonMap("aaa", 3).entrySet().spliterator()).toMap());
assertEquals(Collections.singletonMap("aaa", 3), EntryStream.of(
@@ -192,7 +192,6 @@ public void testWithIndex() {
assertNotEquals(entry, new Object());
assertEquals(new AbstractMap.SimpleImmutableEntry<>(0, "a"), entry);
assertEquals(entry, new AbstractMap.SimpleImmutableEntry<>(0, "a"));
-
assertThrows(UnsupportedOperationException.class, () ->
EntryStream.of(Collections.singletonList("1")).forEach(e -> e.setValue("2")));
}
diff --git a/src/test/java/one/util/streamex/IntCollectorTest.java b/src/test/java/one/util/streamex/api/IntCollectorTest.java
similarity index 97%
rename from src/test/java/one/util/streamex/IntCollectorTest.java
rename to src/test/java/one/util/streamex/api/IntCollectorTest.java
index ab3ed184..84c2d026 100644
--- a/src/test/java/one/util/streamex/IntCollectorTest.java
+++ b/src/test/java/one/util/streamex/api/IntCollectorTest.java
@@ -1,245 +1,249 @@
-/*
- * Copyright 2015, 2019 StreamEx contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package one.util.streamex;
-
-import java.util.BitSet;
-import java.util.IntSummaryStatistics;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-
-import static one.util.streamex.TestHelpers.withRandom;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-/**
- * @author Tagir Valeev
- */
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class IntCollectorTest {
- @Test
- public void testJoining() {
- String expected = IntStream.range(0, 10000).mapToObj(String::valueOf).collect(Collectors.joining(", "));
- assertEquals(expected, IntStreamEx.range(10000).collect(IntCollector.joining(", ")));
- assertEquals(expected, IntStreamEx.range(10000).parallel().collect(IntCollector.joining(", ")));
- String expected2 = IntStreamEx.range(0, 1000).boxed().toList().toString();
- assertEquals(expected2, IntStreamEx.range(1000).collect(IntCollector.joining(", ", "[", "]")));
- assertEquals(expected2, IntStreamEx.range(1000).parallel().collect(IntCollector.joining(", ", "[", "]")));
- }
-
- @Test
- public void testCounting() {
- assertEquals(5000L, (long) IntStreamEx.range(10000).atLeast(5000).collect(IntCollector.counting()));
- assertEquals(5000L, (long) IntStreamEx.range(10000).parallel().atLeast(5000).collect(IntCollector.counting()));
- assertEquals(5000, (int) IntStreamEx.range(10000).atLeast(5000).collect(IntCollector.countingInt()));
- assertEquals(5000, (int) IntStreamEx.range(10000).parallel().atLeast(5000).collect(IntCollector.countingInt()));
- }
-
- @Test
- public void testReducing() {
- assertEquals(120, (int) IntStreamEx.rangeClosed(1, 5).collect(IntCollector.reducing(1, (a, b) -> a * b)));
- assertEquals(120, (int) IntStreamEx.rangeClosed(1, 5).parallel().collect(
- IntCollector.reducing(1, (a, b) -> a * b)));
- }
-
- @Test
- public void testCollectingAndThen() {
- assertEquals(9, (int) IntStreamEx.rangeClosed(1, 5).collect(IntCollector.joining(",").andThen(String::length)));
- }
-
- @Test
- public void testSumming() {
- assertEquals(3725, (int) IntStreamEx.range(100).atLeast(50).collect(IntCollector.summing()));
- assertEquals(3725, (int) IntStreamEx.range(100).parallel().atLeast(50).collect(IntCollector.summing()));
-
- withRandom(r -> {
- int[] input = IntStreamEx.of(r, 10000, 1, 1000).toArray();
- Map expected = IntStream.of(input).boxed().collect(
- Collectors.partitioningBy(i -> i % 2 == 0, Collectors.summingInt(Integer::intValue)));
- Map sumEvenOdd = IntStreamEx.of(input).collect(
- IntCollector.partitioningBy(i -> i % 2 == 0, IntCollector.summing()));
- assertEquals(expected, sumEvenOdd);
- sumEvenOdd = IntStreamEx.of(input).parallel().collect(
- IntCollector.partitioningBy(i -> i % 2 == 0, IntCollector.summing()));
- assertEquals(expected, sumEvenOdd);
- });
- }
-
- @Test
- public void testMin() {
- assertEquals(50, IntStreamEx.range(100).atLeast(50).collect(IntCollector.min()).getAsInt());
- assertFalse(IntStreamEx.range(100).atLeast(200).collect(IntCollector.min()).isPresent());
- }
-
- @Test
- public void testMax() {
- assertEquals(99, IntStreamEx.range(100).atLeast(50).collect(IntCollector.max()).getAsInt());
- assertEquals(99, IntStreamEx.range(100).parallel().atLeast(50).collect(IntCollector.max()).getAsInt());
- assertFalse(IntStreamEx.range(100).atLeast(200).collect(IntCollector.max()).isPresent());
- }
-
- @Test
- public void testSummarizing() {
- withRandom(r -> {
- int[] data = IntStreamEx.of(r, 1000, 1, Integer.MAX_VALUE).toArray();
- IntSummaryStatistics expected = IntStream.of(data).summaryStatistics();
- IntSummaryStatistics statistics = IntStreamEx.of(data).collect(IntCollector.summarizing());
- assertEquals(expected.getCount(), statistics.getCount());
- assertEquals(expected.getSum(), statistics.getSum());
- assertEquals(expected.getMax(), statistics.getMax());
- assertEquals(expected.getMin(), statistics.getMin());
- statistics = IntStreamEx.of(data).parallel().collect(IntCollector.summarizing());
- assertEquals(expected.getCount(), statistics.getCount());
- assertEquals(expected.getSum(), statistics.getSum());
- assertEquals(expected.getMax(), statistics.getMax());
- assertEquals(expected.getMin(), statistics.getMin());
- });
- }
-
- @Test
- public void testToArray() {
- assertArrayEquals(new int[] { 0, 1, 2, 3, 4 }, IntStreamEx.of(0, 1, 2, 3, 4).collect(IntCollector.toArray()));
- assertArrayEquals(IntStreamEx.range(1000).toByteArray(), IntStreamEx.range(1000).collect(
- IntCollector.toByteArray()));
- assertArrayEquals(IntStreamEx.range(1000).toCharArray(), IntStreamEx.range(1000).collect(
- IntCollector.toCharArray()));
- assertArrayEquals(IntStreamEx.range(1000).toShortArray(), IntStreamEx.range(1000).collect(
- IntCollector.toShortArray()));
- }
-
- @SuppressWarnings("SuspiciousMethodCalls")
- @Test
- public void testPartitioning() {
- int[] expectedEven = IntStream.range(0, 1000).map(i -> i * 2).toArray();
- int[] expectedOdd = IntStream.range(0, 1000).map(i -> i * 2 + 1).toArray();
- Map oddEven = IntStreamEx.range(2000).collect(IntCollector.partitioningBy(i -> i % 2 == 0));
- assertTrue(oddEven.containsKey(true));
- assertTrue(oddEven.containsKey(false));
- assertFalse(oddEven.containsKey(null));
- assertFalse(oddEven.containsKey(0));
- assertArrayEquals(expectedEven, oddEven.get(true));
- assertArrayEquals(expectedOdd, oddEven.get(false));
- assertNull(oddEven.get(null));
- assertNull(oddEven.get(0));
- assertEquals(2, oddEven.entrySet().size());
- oddEven = IntStreamEx.range(2000).parallel().collect(IntCollector.partitioningBy(i -> i % 2 == 0));
- assertArrayEquals(expectedEven, oddEven.get(true));
- assertArrayEquals(expectedOdd, oddEven.get(false));
-
- IntCollector, Map