Search in sources :

Example 6 with Function

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

the class SplittableRandomTest method intsDataProvider.

@DataProvider(name = "ints")
public static Object[][] intsDataProvider() {
    List<Object[]> data = new ArrayList<>();
    // Function to create a stream using a RandomBoxedSpliterator
    Function<Function<SplittableRandom, Integer>, IntStream> rbsf = sf -> StreamSupport.stream(new RandomBoxedSpliterator<>(new SplittableRandom(), 0, SIZE, sf), false).mapToInt(i -> i);
    // Unbounded
    data.add(new Object[] { TestData.Factory.ofIntSupplier(String.format("new SplittableRandom().ints().limit(%d)", SIZE), () -> new SplittableRandom().ints().limit(SIZE)), randomAsserter(SIZE, Integer.MAX_VALUE, 0) });
    data.add(new Object[] { TestData.Factory.ofIntSupplier(String.format("new SplittableRandom().ints(%d)", SIZE), () -> new SplittableRandom().ints(SIZE)), randomAsserter(SIZE, Integer.MAX_VALUE, 0) });
    data.add(new Object[] { TestData.Factory.ofIntSupplier(String.format("new RandomBoxedSpliterator(0, %d, sr -> sr.nextInt())", SIZE), () -> rbsf.apply(sr -> sr.nextInt())), randomAsserter(SIZE, Integer.MAX_VALUE, 0) });
    for (int b : BOUNDS) {
        for (int o : ORIGINS) {
            final int origin = o;
            final int bound = b;
            data.add(new Object[] { TestData.Factory.ofIntSupplier(String.format("new SplittableRandom().ints(%d, %d).limit(%d)", origin, bound, SIZE), () -> new SplittableRandom().ints(origin, bound).limit(SIZE)), randomAsserter(SIZE, origin, bound) });
            data.add(new Object[] { TestData.Factory.ofIntSupplier(String.format("new SplittableRandom().ints(%d, %d, %d)", SIZE, origin, bound), () -> new SplittableRandom().ints(SIZE, origin, bound)), randomAsserter(SIZE, origin, bound) });
            if (origin == 0) {
                data.add(new Object[] { TestData.Factory.ofIntSupplier(String.format("new RandomBoxedSpliterator(0, %d, sr -> sr.nextInt(%d))", SIZE, bound), () -> rbsf.apply(sr -> sr.nextInt(bound))), randomAsserter(SIZE, origin, bound) });
            }
            data.add(new Object[] { TestData.Factory.ofIntSupplier(String.format("new RandomBoxedSpliterator(0, %d, sr -> sr.nextInt(%d, %d))", SIZE, origin, bound), () -> rbsf.apply(sr -> sr.nextInt(origin, bound))), randomAsserter(SIZE, origin, bound) });
        }
    }
    return data.toArray(new Object[0][]);
}
Also used : DataProvider(org.testng.annotations.DataProvider) Spliterator(java8.util.Spliterator) IntStream(java8.util.stream.IntStream) OpTestCase(java8.util.stream.OpTestCase) Set(java.util.Set) Test(org.testng.annotations.Test) Spliterators(java8.util.Spliterators) SplittableRandom(java8.util.SplittableRandom) LongStreamTestScenario(java8.util.stream.LongStreamTestScenario) LongStream(java8.util.stream.LongStream) StreamSupport(java8.util.stream.StreamSupport) TestData(java8.util.stream.TestData) Function(java8.util.function.Function) IntStreamTestScenario(java8.util.stream.IntStreamTestScenario) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) List(java.util.List) Consumer(java8.util.function.Consumer) DoubleStream(java8.util.stream.DoubleStream) Comparator(java.util.Comparator) DoubleStreamTestScenario(java8.util.stream.DoubleStreamTestScenario) Function(java8.util.function.Function) ArrayList(java.util.ArrayList) IntStream(java8.util.stream.IntStream) SplittableRandom(java8.util.SplittableRandom) DataProvider(org.testng.annotations.DataProvider)

Example 7 with Function

use of java8.util.function.Function 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 8 with Function

use of java8.util.function.Function 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 9 with Function

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

the class CompletableFutureTest method testHandle_normalCompletion.

/**
 * handle action completes normally with function value on normal
 * completion of source
 */
public void testHandle_normalCompletion() {
    for (ExecutionMode m : ExecutionMode.values()) for (boolean createIncomplete : new boolean[] { true, false }) for (Integer v1 : new Integer[] { 1, null }) {
        final CompletableFuture<Integer> f = new CompletableFuture<>();
        final AtomicInteger a = new AtomicInteger(0);
        if (!createIncomplete)
            assertTrue(f.complete(v1));
        final CompletableFuture<Integer> g = m.handle(f, (Integer result, Throwable t) -> {
            m.checkExecutionMode();
            threadAssertSame(result, v1);
            threadAssertNull(t);
            a.getAndIncrement();
            return inc(v1);
        });
        if (createIncomplete)
            assertTrue(f.complete(v1));
        checkCompletedNormally(g, inc(v1));
        checkCompletedNormally(f, v1);
        assertEquals(1, a.get());
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompletableFuture(java8.util.concurrent.CompletableFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 10 with Function

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

the class FindAnyOpTest method exerciseDoubleStream.

void exerciseDoubleStream(TestData.OfDouble data, Function<DoubleStream, DoubleStream> fs) {
    OptionalDouble or = withData(data).terminal(fs, s -> s.findAny()).equalator(DOUBLE_VALID_ANSWER).exercise();
    if (or.isPresent()) {
        double r = or.getAsDouble();
        PrimitiveIterator.OfDouble it = fs.apply(data.stream()).iterator();
        boolean contained = false;
        while (!contained && it.hasNext()) {
            contained = r == it.nextDouble();
        }
        assertTrue(contained);
    } else {
        assertFalse(fs.apply(data.stream()).iterator().hasNext());
    }
}
Also used : PrimitiveIterator(java8.util.PrimitiveIterator) OptionalDouble(java8.util.OptionalDouble)

Aggregations

Function (java8.util.function.Function)7 Test (org.testng.annotations.Test)7 List (java.util.List)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 OpTestCase (java8.util.stream.OpTestCase)6 StreamSupport (java8.util.stream.StreamSupport)6 ArrayList (java.util.ArrayList)5 Set (java.util.Set)5 CompletableFuture (java8.util.concurrent.CompletableFuture)5 Consumer (java8.util.function.Consumer)5 TestData (java8.util.stream.TestData)5 HashSet (java.util.HashSet)4 Spliterator (java8.util.Spliterator)4 Supplier (java8.util.function.Supplier)4 DoubleStream (java8.util.stream.DoubleStream)4 IntStream (java8.util.stream.IntStream)4 LongStream (java8.util.stream.LongStream)4 Comparator (java.util.Comparator)3 PrimitiveIterator (java8.util.PrimitiveIterator)3 CompletionException (java8.util.concurrent.CompletionException)3