Search in sources :

Example 11 with Supplier

use of java8.util.function.Supplier in project streamsupport by stefan-zobel.

the class FlatMapOpTest method testClose.

@Test
public void testClose() {
    AtomicInteger before = new AtomicInteger();
    AtomicInteger onClose = new AtomicInteger();
    Supplier<Stream<Integer>> s = () -> {
        before.set(0);
        onClose.set(0);
        return RefStreams.of(1, 2).peek(e -> before.getAndIncrement());
    };
    s.get().flatMap(i -> RefStreams.of(i, i).onClose(onClose::getAndIncrement)).count();
    assertEquals(before.get(), onClose.get());
    s.get().flatMapToInt(i -> IntStreams.of(i, i).onClose(onClose::getAndIncrement)).count();
    assertEquals(before.get(), onClose.get());
    s.get().flatMapToLong(i -> LongStreams.of(i, i).onClose(onClose::getAndIncrement)).count();
    assertEquals(before.get(), onClose.get());
    s.get().flatMapToDouble(i -> DoubleStreams.of(i, i).onClose(onClose::getAndIncrement)).count();
    assertEquals(before.get(), onClose.get());
}
Also used : Arrays(java.util.Arrays) DoubleStreams(java8.util.stream.DoubleStreams) Collection(java.util.Collection) LongStreamTestDataProvider(java8.util.stream.LongStreamTestDataProvider) OpTestCase(java8.util.stream.OpTestCase) Test(org.testng.annotations.Test) DoubleStreamTestDataProvider(java8.util.stream.DoubleStreamTestDataProvider) StreamSupport(java8.util.stream.StreamSupport) TestData(java8.util.stream.TestData) Function(java8.util.function.Function) Supplier(java8.util.function.Supplier) IntStreams(java8.util.stream.IntStreams) LambdaTestHelpers(java8.util.stream.LambdaTestHelpers) LongStreams(java8.util.stream.LongStreams) ThrowableHelper.checkNPE(java8.util.stream.ThrowableHelper.checkNPE) RefStreams(java8.util.stream.RefStreams) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StreamTestDataProvider(java8.util.stream.StreamTestDataProvider) IntStreamTestDataProvider(java8.util.stream.IntStreamTestDataProvider) Stream(java8.util.stream.Stream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Stream(java8.util.stream.Stream) Test(org.testng.annotations.Test)

Example 12 with Supplier

use of java8.util.function.Supplier in project streamsupport by stefan-zobel.

the class TestDoubleSumAverage method testNonfiniteSum.

private static int testNonfiniteSum() {
    int failures = 0;
    Map<Supplier<DoubleStream>, Double> testCases = new LinkedHashMap<Supplier<DoubleStream>, Double>();
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(MAX_VALUE, MAX_VALUE);
        }
    }, POSITIVE_INFINITY);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(-MAX_VALUE, -MAX_VALUE);
        }
    }, NEGATIVE_INFINITY);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(1.0d, POSITIVE_INFINITY, 1.0d);
        }
    }, POSITIVE_INFINITY);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(POSITIVE_INFINITY);
        }
    }, POSITIVE_INFINITY);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(POSITIVE_INFINITY, POSITIVE_INFINITY);
        }
    }, POSITIVE_INFINITY);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(POSITIVE_INFINITY, POSITIVE_INFINITY, 0.0);
        }
    }, POSITIVE_INFINITY);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(1.0d, NEGATIVE_INFINITY, 1.0d);
        }
    }, NEGATIVE_INFINITY);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(NEGATIVE_INFINITY);
        }
    }, NEGATIVE_INFINITY);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(NEGATIVE_INFINITY, NEGATIVE_INFINITY);
        }
    }, NEGATIVE_INFINITY);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(NEGATIVE_INFINITY, NEGATIVE_INFINITY, 0.0);
        }
    }, NEGATIVE_INFINITY);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(1.0d, NaN, 1.0d);
        }
    }, NaN);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(NaN);
        }
    }, NaN);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(1.0d, NEGATIVE_INFINITY, POSITIVE_INFINITY, 1.0d);
        }
    }, NaN);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(1.0d, POSITIVE_INFINITY, NEGATIVE_INFINITY, 1.0d);
        }
    }, NaN);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(POSITIVE_INFINITY, NaN);
        }
    }, NaN);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(NEGATIVE_INFINITY, NaN);
        }
    }, NaN);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(NaN, POSITIVE_INFINITY);
        }
    }, NaN);
    testCases.put(new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.of(NaN, NEGATIVE_INFINITY);
        }
    }, NaN);
    for (Map.Entry<Supplier<DoubleStream>, Double> testCase : testCases.entrySet()) {
        Supplier<DoubleStream> ds = testCase.getKey();
        double expected = testCase.getValue();
        DoubleSummaryStatistics stats = ds.get().collect(new Supplier<DoubleSummaryStatistics>() {

            @Override
            public DoubleSummaryStatistics get() {
                return new DoubleSummaryStatistics();
            }
        }, (ObjDoubleConsumer<DoubleSummaryStatistics>) new ObjDoubleConsumer<DoubleSummaryStatistics>() {

            @Override
            public void accept(DoubleSummaryStatistics doubleSummaryStatistics, double v) {
                doubleSummaryStatistics.accept(v);
            }
        }, (BiConsumer<DoubleSummaryStatistics, DoubleSummaryStatistics>) new BiConsumer<DoubleSummaryStatistics, DoubleSummaryStatistics>() {

            @Override
            public void accept(DoubleSummaryStatistics doubleSummaryStatistics, DoubleSummaryStatistics doubleSummaryStatistics2) {
                doubleSummaryStatistics.combine(doubleSummaryStatistics2);
            }
        });
        failures += compareUlpDifference(expected, stats.getSum(), 0);
        failures += compareUlpDifference(expected, stats.getAverage(), 0);
        failures += compareUlpDifference(expected, ds.get().sum(), 0);
        failures += compareUlpDifference(expected, ds.get().average().getAsDouble(), 0);
        failures += compareUlpDifference(expected, ds.get().boxed().collect(Collectors.summingDouble(new ToDoubleFunction<Double>() {

            @Override
            public double applyAsDouble(Double d) {
                return d;
            }
        })), 0);
        failures += compareUlpDifference(expected, ds.get().boxed().collect(Collectors.averagingDouble(new ToDoubleFunction<Double>() {

            @Override
            public double applyAsDouble(Double d) {
                return d;
            }
        })), 0);
    }
    return failures;
}
Also used : DoubleSummaryStatistics(java8.util.DoubleSummaryStatistics) Double(java.lang.Double)

Example 13 with Supplier

use of java8.util.function.Supplier in project streamsupport by stefan-zobel.

the class ConcurrentAssociateTest method testOnce.

private static void testOnce(final String desc, final BiConsumer<ConcurrentMap<Object, Object>, Object> associator) {
    final ConcurrentHashMap<Object, Object> m = new ConcurrentHashMap<Object, Object>();
    final CountDownLatch s = new CountDownLatch(1);
    final Supplier<Runnable> putter = new Supplier<Runnable>() {

        @Override
        public Runnable get() {
            return new Runnable() {

                @Override
                public void run() {
                    try {
                        s.await();
                    } catch (InterruptedException e) {
                    }
                    for (int i = 0; i < N; i++) {
                        Object o = new X();
                        associator.accept(m, o);
                        if (!m.containsKey(o)) {
                            throw new AssociationFailure(desc + " failed: entry does not exist");
                        }
                    }
                }
            };
        }
    };
    Stream<CompletableFuture<Void>> putters = IntStreams.range(0, availableProcessors).mapToObj(new IntFunction<Runnable>() {

        public Runnable apply(int i) {
            return putter.get();
        }
    }).map(new Function<Runnable, CompletableFuture<Void>>() {

        @Override
        public CompletableFuture<Void> apply(Runnable runnable) {
            return CompletableFuture.runAsync(runnable);
        }
    });
    CompletableFuture<Void> all = CompletableFuture.allOf(putters.toArray(new IntFunction<CompletableFuture<Void>[]>() {

        @Override
        @SuppressWarnings("unchecked")
        public CompletableFuture<Void>[] apply(int size) {
            return (CompletableFuture<Void>[]) new CompletableFuture[size];
        }
    }));
    // Trigger the runners to start
    s.countDown();
    try {
        all.join();
    } catch (CompletionException e) {
        Throwable t = e.getCause();
        if (t instanceof AssociationFailure) {
            throw (AssociationFailure) t;
        } else {
            throw e;
        }
    }
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) CompletableFuture(java8.util.concurrent.CompletableFuture) IntFunction(java8.util.function.IntFunction) CompletionException(java8.util.concurrent.CompletionException) Supplier(java8.util.function.Supplier) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 14 with Supplier

use of java8.util.function.Supplier in project streamsupport by stefan-zobel.

the class WhileOpStatefulTest method testWhileMulti.

private void testWhileMulti(Map<String, Supplier<Stream<Integer>>> sources, Consumer<Stream<Integer>> mRef, Consumer<IntStream> mInt, Consumer<LongStream> mLong, Consumer<DoubleStream> mDouble) {
    Map<String, Function<Stream<Integer>, Stream<Integer>>> transforms = new HashMap<>();
    transforms.put("Stream.sequential()", s -> {
        BooleanSupplier isWithinExecutionPeriod = within(System.currentTimeMillis(), EXECUTION_TIME_LIMIT);
        return s.peek(e -> {
            if (!isWithinExecutionPeriod.getAsBoolean()) {
                throw new RuntimeException();
            }
        });
    });
    transforms.put("Stream.parallel()", s -> {
        BooleanSupplier isWithinExecutionPeriod = within(System.currentTimeMillis(), EXECUTION_TIME_LIMIT);
        return s.parallel().peek(e -> {
            if (!isWithinExecutionPeriod.getAsBoolean()) {
                throw new RuntimeException();
            }
        });
    });
    Map<String, Consumer<Stream<Integer>>> actions = new HashMap<>();
    actions.put("Ref", mRef);
    actions.put("Int", s -> mInt.accept(s.mapToInt(e -> e)));
    actions.put("Long", s -> mLong.accept(s.mapToLong(e -> e)));
    actions.put("Double", s -> mDouble.accept(s.mapToDouble(e -> e)));
    actions.put("Ref using defaults", s -> mRef.accept(DefaultMethodStreams.delegateTo(s)));
    actions.put("Int using defaults", s -> mInt.accept(DefaultMethodStreams.delegateTo(s.mapToInt(e -> e))));
    actions.put("Long using defaults", s -> mLong.accept(DefaultMethodStreams.delegateTo(s.mapToLong(e -> e))));
    actions.put("Double using defaults", s -> mDouble.accept(DefaultMethodStreams.delegateTo(s.mapToDouble(e -> e))));
    for (Map.Entry<String, Supplier<Stream<Integer>>> s : sources.entrySet()) {
        setContext("source", s.getKey());
        for (Map.Entry<String, Function<Stream<Integer>, Stream<Integer>>> t : transforms.entrySet()) {
            setContext("transform", t.getKey());
            for (Map.Entry<String, Consumer<Stream<Integer>>> a : actions.entrySet()) {
                setContext("shape", a.getKey());
                Stream<Integer> stream = s.getValue().get();
                stream = t.getValue().apply(stream);
                a.getValue().accept(stream);
            }
        }
    }
}
Also used : Collector(java8.util.stream.Collector) IntStream(java8.util.stream.IntStream) OpTestCase(java8.util.stream.OpTestCase) Test(org.testng.annotations.Test) HashMap(java.util.HashMap) LongStream(java8.util.stream.LongStream) StreamSupport(java8.util.stream.StreamSupport) Function(java8.util.function.Function) Supplier(java8.util.function.Supplier) IntStreams(java8.util.stream.IntStreams) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) RefStreams(java8.util.stream.RefStreams) Collectors.toCollection(java8.util.stream.Collectors.toCollection) Consumer(java8.util.function.Consumer) Map(java.util.Map) DefaultMethodStreams(java8.util.stream.DefaultMethodStreams) BooleanSupplier(java8.util.function.BooleanSupplier) DoubleStream(java8.util.stream.DoubleStream) LinkedList(java.util.LinkedList) Stream(java8.util.stream.Stream) HashMap(java.util.HashMap) Function(java8.util.function.Function) Consumer(java8.util.function.Consumer) Supplier(java8.util.function.Supplier) BooleanSupplier(java8.util.function.BooleanSupplier) BooleanSupplier(java8.util.function.BooleanSupplier) HashMap(java.util.HashMap) Map(java.util.Map)

Example 15 with Supplier

use of java8.util.function.Supplier in project streamsupport by stefan-zobel.

the class Collection8Test method testStreamForEach.

/**
 * stream().forEach returns elements in the collection
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(dataProvider = "Source")
public void testStreamForEach(String description, Supplier<CollectionImplementation> sci) throws Throwable {
    CollectionImplementation impl = sci.get();
    final Collection c = impl.emptyCollection();
    // final AtomicLong count = new AtomicLong(0L);
    final Object x = impl.makeElement(1);
    final Object y = impl.makeElement(2);
    final ArrayList found = new ArrayList();
    Consumer<Object> spy = o -> found.add(o);
    StreamSupport.stream(c).forEach(spy);
    assertTrue(found.isEmpty());
    assertTrue(c.add(x));
    StreamSupport.stream(c).forEach(spy);
    assertEquals(Collections.singletonList(x), found);
    found.clear();
    assertTrue(c.add(y));
    StreamSupport.stream(c).forEach(spy);
    assertEquals(2, found.size());
    assertTrue(found.contains(x));
    assertTrue(found.contains(y));
    found.clear();
    c.clear();
    StreamSupport.stream(c).forEach(spy);
    assertTrue(found.isEmpty());
}
Also used : Arrays(java.util.Arrays) DataProvider(org.testng.annotations.DataProvider) PriorityQueue(java.util.PriorityQueue) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.testng.annotations.Test) Iterables(java8.lang.Iterables) Deque(java.util.Deque) Predicate(java8.util.function.Predicate) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) PriorityBlockingQueue(java.util.concurrent.PriorityBlockingQueue) HashSet(java.util.HashSet) Phaser(java8.util.concurrent.Phaser) Iterators(java8.util.Iterators) Future(java.util.concurrent.Future) J8Arrays(java8.util.J8Arrays) Vector(java.util.Vector) Consumer(java8.util.function.Consumer) LinkedList(java.util.LinkedList) NoSuchElementException(java.util.NoSuchElementException) ExecutorService(java.util.concurrent.ExecutorService) Iterator(java.util.Iterator) BlockingDeque(java.util.concurrent.BlockingDeque) Collection(java.util.Collection) Spliterator(java8.util.Spliterator) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) Collectors(java8.util.stream.Collectors) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Spliterators(java8.util.Spliterators) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) StreamSupport(java8.util.stream.StreamSupport) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Executors(java.util.concurrent.Executors) Supplier(java8.util.function.Supplier) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) ThreadLocalRandom(java8.util.concurrent.ThreadLocalRandom) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) HOURS(java.util.concurrent.TimeUnit.HOURS) Queue(java.util.Queue) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) ConcurrentModificationException(java.util.ConcurrentModificationException) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Collection(java.util.Collection) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)16 Collection (java.util.Collection)14 LinkedList (java.util.LinkedList)13 ThreadLocalRandom (java8.util.concurrent.ThreadLocalRandom)13 Supplier (java8.util.function.Supplier)13 ArrayList (java.util.ArrayList)12 List (java.util.List)12 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)12 ArrayDeque (java.util.ArrayDeque)11 Deque (java.util.Deque)11 HashSet (java.util.HashSet)11 BlockingDeque (java.util.concurrent.BlockingDeque)11 LinkedBlockingDeque (java.util.concurrent.LinkedBlockingDeque)11 Spliterator (java8.util.Spliterator)11 StreamSupport (java8.util.stream.StreamSupport)11 Arrays (java.util.Arrays)10 ConcurrentModificationException (java.util.ConcurrentModificationException)10 Iterator (java.util.Iterator)10 Set (java.util.Set)10 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)10