Search in sources :

Example 6 with Supplier

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

the class Collection8Test method testRemoveAfterForEachRemaining.

/**
 * Calling Iterator#remove() after Iterator#forEachRemaining
 * should (maybe) remove last element
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(dataProvider = "Source")
public void testRemoveAfterForEachRemaining(String description, Supplier<CollectionImplementation> sci) {
    CollectionImplementation impl = sci.get();
    Collection c = impl.emptyCollection();
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    testCollection: {
        int n = 3 + rnd.nextInt(2);
        for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
        Iterator<?> it = c.iterator();
        assertTrue(it.hasNext());
        assertEquals(impl.makeElement(0), it.next());
        assertTrue(it.hasNext());
        assertEquals(impl.makeElement(1), it.next());
        Iterators.forEachRemaining(it, e -> assertTrue(c.contains(e)));
        if (testImplementationDetails) {
            if (c instanceof java.util.concurrent.ArrayBlockingQueue) {
                assertIteratorExhausted(it);
            } else {
                try {
                    it.remove();
                } catch (UnsupportedOperationException ok) {
                    break testCollection;
                }
                assertEquals(n - 1, c.size());
                for (int i = 0; i < n - 1; i++) assertTrue(c.contains(impl.makeElement(i)));
                assertFalse(c.contains(impl.makeElement(n - 1)));
            }
        }
    }
    if (c instanceof Deque) {
        Deque d = (Deque) impl.emptyCollection();
        int n = 3 + rnd.nextInt(2);
        for (int i = 0; i < n; i++) d.add(impl.makeElement(i));
        Iterator<?> it = d.descendingIterator();
        assertTrue(it.hasNext());
        assertEquals(impl.makeElement(n - 1), it.next());
        assertTrue(it.hasNext());
        assertEquals(impl.makeElement(n - 2), it.next());
        Iterators.forEachRemaining(it, e -> assertTrue(c.contains(e)));
        if (testImplementationDetails) {
            it.remove();
            assertEquals(n - 1, d.size());
            for (int i = 1; i < n; i++) assertTrue(d.contains(impl.makeElement(i)));
            assertFalse(d.contains(impl.makeElement(0)));
        }
    }
}
Also used : Collection(java.util.Collection) ThreadLocalRandom(java8.util.concurrent.ThreadLocalRandom) Deque(java.util.Deque) BlockingDeque(java.util.concurrent.BlockingDeque) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) ArrayDeque(java.util.ArrayDeque) Test(org.testng.annotations.Test)

Example 7 with Supplier

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

the class Collection8Test method testForEach.

/**
 * collection.forEach returns elements in the collection
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(dataProvider = "Source")
public void testForEach(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);
    Iterables.forEach(c, spy);
    assertTrue(found.isEmpty());
    assertTrue(c.add(x));
    Iterables.forEach(c, spy);
    assertEquals(Collections.singletonList(x), found);
    found.clear();
    assertTrue(c.add(y));
    Iterables.forEach(c, spy);
    assertEquals(2, found.size());
    assertTrue(found.contains(x));
    assertTrue(found.contains(y));
    found.clear();
    c.clear();
    Iterables.forEach(c, 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)

Example 8 with Supplier

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

the class CompletableFutureTest method testCompleteAsync3.

/**
 * completeAsync with given executor completes with value of given supplier
 */
public void testCompleteAsync3() {
    for (Integer v1 : new Integer[] { 1, null }) {
        CompletableFuture<Integer> f = new CompletableFuture<>();
        ThreadExecutor executor = new ThreadExecutor();
        f.completeAsync(() -> v1, executor);
        assertSame(v1, f.join());
        checkCompletedNormally(f, v1);
        assertEquals(1, executor.count.get());
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompletableFuture(java8.util.concurrent.CompletableFuture)

Example 9 with Supplier

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

the class CompletableFutureTest method testCompleteAsync.

/**
 * completeAsync completes with value of given supplier
 */
public void testCompleteAsync() {
    for (Integer v1 : new Integer[] { 1, null }) {
        CompletableFuture<Integer> f = new CompletableFuture<>();
        f.completeAsync(() -> v1);
        f.join();
        checkCompletedNormally(f, v1);
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompletableFuture(java8.util.concurrent.CompletableFuture)

Example 10 with Supplier

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

the class TestDoubleSumAverage method testForCompensation.

/**
 * Compute the sum and average of a sequence of double values in
 * various ways and report an error if naive summation is used.
 */
private static int testForCompensation() {
    int failures = 0;
    /*
         * The exact sum of the test stream is 1 + 1e6*ulp(1.0) but a
         * naive summation algorithm will return 1.0 since (1.0 +
         * ulp(1.0)/2) will round to 1.0 again.
         */
    final double base = 1.0;
    final double increment = Math.ulp(base) / 2.0;
    final int count = 1000001;
    double expectedSum = base + (increment * (count - 1));
    double expectedAvg = expectedSum / count;
    // Factory for double a stream of [base, increment, ..., increment] limited to a size of count
    Supplier<DoubleStream> ds = new Supplier<DoubleStream>() {

        @Override
        public DoubleStream get() {
            return DoubleStreams.iterate(base, new DoubleUnaryOperator() {

                @Override
                public double applyAsDouble(double e) {
                    return increment;
                }
            }).limit(count);
        }
    };
    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(expectedSum, stats.getSum(), 3);
    failures += compareUlpDifference(expectedAvg, stats.getAverage(), 3);
    failures += compareUlpDifference(expectedSum, ds.get().sum(), 3);
    failures += compareUlpDifference(expectedAvg, ds.get().average().getAsDouble(), 3);
    failures += compareUlpDifference(expectedSum, ds.get().boxed().collect(Collectors.summingDouble(new ToDoubleFunction<Double>() {

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

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

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