Java Code Examples for java.util.function.UnaryOperator

The following examples show how to use java.util.function.UnaryOperator. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private static <T, S extends Spliterator<T>> void testSplitSixDeep(
        Collection<T> exp,
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    S spliterator = supplier.get();
    boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);

    for (int depth=0; depth < 6; depth++) {
        List<T> dest = new ArrayList<>();
        spliterator = supplier.get();

        assertSpliterator(spliterator);

        // verify splitting with forEach
        visit(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), false);
        assertContents(dest, exp, isOrdered);

        // verify splitting with tryAdvance
        dest.clear();
        spliterator = supplier.get();
        visit(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), true);
        assertContents(dest, exp, isOrdered);
    }
}
 
Example 2
private static <T, S extends Spliterator<T>> void testSplitAfterFullTraversal(
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    // Full traversal using tryAdvance
    Spliterator<T> spliterator = supplier.get();
    while (spliterator.tryAdvance(boxingAdapter.apply(e -> { }))) { }
    Spliterator<T> split = spliterator.trySplit();
    assertNull(split);

    // Full traversal using forEach
    spliterator = supplier.get();
    spliterator.forEachRemaining(boxingAdapter.apply(e -> {
    }));
    split = spliterator.trySplit();
    assertNull(split);

    // Full traversal using tryAdvance then forEach
    spliterator = supplier.get();
    spliterator.tryAdvance(boxingAdapter.apply(e -> { }));
    spliterator.forEachRemaining(boxingAdapter.apply(e -> {
    }));
    split = spliterator.trySplit();
    assertNull(split);
}
 
Example 3
private static <T, S extends Spliterator<T>> void testSplitOnce(
        Collection<T> exp,
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    S spliterator = supplier.get();
    long sizeIfKnown = spliterator.getExactSizeIfKnown();
    boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);

    ArrayList<T> fromSplit = new ArrayList<>();
    Spliterator<T> s1 = supplier.get();
    Spliterator<T> s2 = s1.trySplit();
    long s1Size = s1.getExactSizeIfKnown();
    long s2Size = (s2 != null) ? s2.getExactSizeIfKnown() : 0;
    Consumer<T> addToFromSplit = boxingAdapter.apply(fromSplit::add);
    if (s2 != null)
        s2.forEachRemaining(addToFromSplit);
    s1.forEachRemaining(addToFromSplit);

    if (sizeIfKnown >= 0) {
        assertEquals(sizeIfKnown, fromSplit.size());
        if (s1Size >= 0 && s2Size >= 0)
            assertEquals(sizeIfKnown, s1Size + s2Size);
    }
    assertContents(fromSplit, exp, isOrdered);
}
 
Example 4
@Test
public void testFrom() {
    // act/assert
    Assert.assertArrayEquals(new double[] {
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0
    }, AffineTransformMatrix3D.from(UnaryOperator.identity()).toArray(), EPS);
    Assert.assertArrayEquals(new double[] {
        1, 0, 0, 2,
        0, 1, 0, 3,
        0, 0, 1, -4
    }, AffineTransformMatrix3D.from(v -> v.add(Vector3D.of(2, 3, -4))).toArray(), EPS);
    Assert.assertArrayEquals(new double[] {
        3, 0, 0, 0,
        0, 3, 0, 0,
        0, 0, 3, 0
    }, AffineTransformMatrix3D.from(v -> v.multiply(3)).toArray(), EPS);
    Assert.assertArrayEquals(new double[] {
        3, 0, 0, 6,
        0, 3, 0, 9,
        0, 0, 3, 12
    }, AffineTransformMatrix3D.from(v -> v.add(Vector3D.of(2, 3, 4)).multiply(3)).toArray(), EPS);
}
 
Example 5
Source Project: streams-utils   Source File: ValidatingSpliteratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_validated_a_stream_correctly_with_one_transformation_for_invalid_elements() {
    // Given
    Stream<String> strings = Stream.of("one", null, "two", null, "three");
    Predicate<String> validator = Objects::nonNull;
    UnaryOperator<String> transformIfNotValid = s -> "";

    // When
    Stream<String> validateStream =
            StreamsUtils.validate(strings, validator, transformIfNotValid);
    List<String> list = validateStream.collect(toList());

    // Then
    assertThat(list.size()).isEqualTo(5);
    assertThat(list).containsExactly("one", "", "two", "", "three");
}
 
Example 6
private static <T, S extends Spliterator<T>> void testSplitAfterFullTraversal(
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    // Full traversal using tryAdvance
    Spliterator<T> spliterator = supplier.get();
    while (spliterator.tryAdvance(boxingAdapter.apply(e -> { }))) { }
    Spliterator<T> split = spliterator.trySplit();
    assertNull(split);

    // Full traversal using forEach
    spliterator = supplier.get();
    spliterator.forEachRemaining(boxingAdapter.apply(e -> {
    }));
    split = spliterator.trySplit();
    assertNull(split);

    // Full traversal using tryAdvance then forEach
    spliterator = supplier.get();
    spliterator.tryAdvance(boxingAdapter.apply(e -> { }));
    spliterator.forEachRemaining(boxingAdapter.apply(e -> {
    }));
    split = spliterator.trySplit();
    assertNull(split);
}
 
Example 7
Source Project: jdk1.8-source-analysis   Source File: Stream.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns an infinite sequential ordered {@code Stream} produced by iterative
 * application of a function {@code f} to an initial element {@code seed},
 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
 * {@code f(f(seed))}, etc.
 *
 * <p>The first element (position {@code 0}) in the {@code Stream} will be
 * the provided {@code seed}.  For {@code n > 0}, the element at position
 * {@code n}, will be the result of applying the function {@code f} to the
 * element at position {@code n - 1}.
 *
 * @param <T> the type of stream elements
 * @param seed the initial element
 * @param f a function to be applied to to the previous element to produce
 *          a new element
 * @return a new sequential {@code Stream}
 */
public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) {
    Objects.requireNonNull(f);
    final Iterator<T> iterator = new Iterator<T>() {
        @SuppressWarnings("unchecked")
        T t = (T) Streams.NONE;

        @Override
        public boolean hasNext() {
            return true;
        }

        @Override
        public T next() {
            return t = (t == Streams.NONE) ? seed : f.apply(t);
        }
    };
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
            iterator,
            Spliterator.ORDERED | Spliterator.IMMUTABLE), false);
}
 
Example 8
private static <T, S extends Spliterator<T>> void testSplitSixDeep(
        Collection<T> exp,
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    S spliterator = supplier.get();
    boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);

    for (int depth=0; depth < 6; depth++) {
        List<T> dest = new ArrayList<>();
        spliterator = supplier.get();

        assertSpliterator(spliterator);

        // verify splitting with forEach
        visit(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), false);
        assertContents(dest, exp, isOrdered);

        // verify splitting with tryAdvance
        dest.clear();
        spliterator = supplier.get();
        visit(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), true);
        assertContents(dest, exp, isOrdered);
    }
}
 
Example 9
private static <T, S extends Spliterator<T>> void testSplitOnce(
        Collection<T> exp,
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    S spliterator = supplier.get();
    long sizeIfKnown = spliterator.getExactSizeIfKnown();
    boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);

    ArrayList<T> fromSplit = new ArrayList<>();
    Spliterator<T> s1 = supplier.get();
    Spliterator<T> s2 = s1.trySplit();
    long s1Size = s1.getExactSizeIfKnown();
    long s2Size = (s2 != null) ? s2.getExactSizeIfKnown() : 0;

    Consumer<T> addToFromSplit = boxingAdapter.apply(fromSplit::add);
    if (s2 != null)
        s2.forEachRemaining(addToFromSplit);
    s1.forEachRemaining(addToFromSplit);

    if (sizeIfKnown >= 0) {
        assertEquals(sizeIfKnown, fromSplit.size());
        if (s1Size >= 0 && s2Size >= 0)
            assertEquals(sizeIfKnown, s1Size + s2Size);
    }
    assertContents(fromSplit, exp, isOrdered);
}
 
Example 10
Source Project: commons-rng   Source File: RngDataOutputTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the RNG and then creates bytes from the RNG using the pipe.
 *
 * @param rng RNG.
 * @param size The number of values to send to the pipe.
 * @param repeats The number of repeat iterations.
 * @param rngConverter Converter for the raw RNG.
 * @param pipe Pipe to send data from the RNG to the DataOutputStream.
 * @return the bytes
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static byte[] createBytes(UniformRandomProvider rng, int size, int repeats,
    UnaryOperator<UniformRandomProvider> rngConverter,
    BiConsumer<DataOutputStream, UniformRandomProvider> pipe) throws IOException {
    UniformRandomProvider rng2 = rngConverter.apply(rng);
    // If the factory converts to an IntProvider then output twice the size
    if (rng instanceof RandomLongSource && rng2 instanceof RandomIntSource) {
        size *= 2;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (DataOutputStream sink = new DataOutputStream(out)) {
        for (int j = 0; j < repeats; j++) {
            for (int i = 0; i < size; i++) {
                pipe.accept(sink, rng2);
            }
        }
    }
    return out.toByteArray();
}
 
Example 11
public void replaceAll(UnaryOperator<E> operator) {
    if (operator == null) throw new NullPointerException();
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] elements = getArray();
        int len = elements.length;
        Object[] newElements = Arrays.copyOf(elements, len);
        for (int i = 0; i < len; ++i) {
            @SuppressWarnings("unchecked") E e = (E) elements[i];
            newElements[i] = operator.apply(e);
        }
        setArray(newElements);
    } finally {
        lock.unlock();
    }
}
 
Example 12
private static <T, S extends Spliterator<T>> void testTryAdvance(
        Collection<T> exp,
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    S spliterator = supplier.get();
    long sizeIfKnown = spliterator.getExactSizeIfKnown();
    boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);

    spliterator = supplier.get();
    ArrayList<T> fromTryAdvance = new ArrayList<>();
    Consumer<T> addToFromTryAdvance = boxingAdapter.apply(fromTryAdvance::add);
    while (spliterator.tryAdvance(addToFromTryAdvance)) { }

    // Assert that forEach now produces no elements
    spliterator.forEachRemaining(boxingAdapter.apply(e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
    // Assert that tryAdvance now produce no elements
    spliterator.tryAdvance(boxingAdapter.apply(e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));

    // assert that size, tryAdvance, and forEach are consistent
    if (sizeIfKnown >= 0) {
        assertEquals(sizeIfKnown, exp.size());
    }
    assertEquals(fromTryAdvance.size(), exp.size());

    assertContents(fromTryAdvance, exp, isOrdered);
}
 
Example 13
Source Project: IPAddress   Source File: IPAddress.java    License: Apache License 2.0 6 votes vote down vote up
protected static <T extends IPAddress, S extends IPAddressSegment> T[] getSpanningSequentialBlocks(
		T first,
		T other,
		UnaryOperator<T> getLower,
		UnaryOperator<T> getUpper,
		Comparator<T> comparator,
		UnaryOperator<T> prefixRemover,
		IPAddressCreator<T, ?, ?, S, ?> creator) {
	T[] result = checkSequentialBlockContainment(first, other, prefixRemover, creator::createAddressArray);
	if(result != null) {
		return result;
	}
	SeriesCreator seriesCreator = createSeriesCreator(creator, first.getMaxSegmentValue());
	TriFunction<T, List<IPAddressSegmentSeries>> operatorFunctor = (orig, one, two) -> IPAddressSection.splitIntoSequentialBlocks(one, two, seriesCreator);
	List<IPAddressSegmentSeries> blocks = IPAddressSection.applyOperatorToLowerUpper(first, other, getLower, getUpper, comparator, prefixRemover, operatorFunctor);
	return blocks.toArray(creator.createAddressArray(blocks.size()));
}
 
Example 14
Source Project: jdk8u-jdk   Source File: SequentialOpTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
public void testMixedSeqPar(String name, TestData.OfRef<Integer> data) {
    Function<Integer, Integer> id = LambdaTestHelpers.identity();
    UnaryOperator<Stream<Integer>>[] changers
            = new UnaryOperator[] {
            (UnaryOperator<Stream<Integer>>) s -> s,
            (UnaryOperator<Stream<Integer>>) s -> s.sequential(),
            (UnaryOperator<Stream<Integer>>) s -> s.parallel(),
            (UnaryOperator<Stream<Integer>>) s -> s.unordered()
    };
    UnaryOperator<Stream<Integer>>[] stuff
            = new UnaryOperator[] {
            (UnaryOperator<Stream<Integer>>) s -> s,
            (UnaryOperator<Stream<Integer>>) s -> s.map(id),
            (UnaryOperator<Stream<Integer>>) s -> s.sorted(Comparator.naturalOrder()),
            (UnaryOperator<Stream<Integer>>) s -> s.map(id).sorted(Comparator.naturalOrder()).map(id),
            (UnaryOperator<Stream<Integer>>) s -> s.filter(LambdaTestHelpers.pEven).sorted(Comparator.naturalOrder()).map(id),
    };

    for (int c1Index = 0; c1Index < changers.length; c1Index++) {
        setContext("c1Index", c1Index);
        UnaryOperator<Stream<Integer>> c1 = changers[c1Index];
        for (int s1Index = 0; s1Index < stuff.length; s1Index++) {
            setContext("s1Index", s1Index);
            UnaryOperator<Stream<Integer>> s1 = stuff[s1Index];
            for (int c2Index = 0; c2Index < changers.length; c2Index++) {
                setContext("c2Index", c2Index);
                UnaryOperator<Stream<Integer>> c2 = changers[c2Index];
                for (int s2Index = 0; s2Index < stuff.length; s2Index++) {
                    setContext("s2Index", s2Index);
                    UnaryOperator<Stream<Integer>> s2 = stuff[s2Index];
                    UnaryOperator<Stream<Integer>> composed = s -> s2.apply(c2.apply(s1.apply(c1.apply(s))));
                    exerciseOps(data, composed);
                }
            }
        }
    }
}
 
Example 15
@DataProvider(name = "DoubleStream.limit")
public static Object[][] doubleSliceFunctionsDataProvider() {
    Function<String, String> f = s -> String.format(s, SKIP_LIMIT_SIZE);

    List<Object[]> data = new ArrayList<>();

    data.add(new Object[]{f.apply("DoubleStream.limit(%d)"),
            (UnaryOperator<DoubleStream>) s -> s.limit(SKIP_LIMIT_SIZE)});
    data.add(new Object[]{f.apply("DoubleStream.skip(%1$d).limit(%1$d)"),
            (UnaryOperator<DoubleStream>) s -> s.skip(SKIP_LIMIT_SIZE).limit(SKIP_LIMIT_SIZE)});

    return data.toArray(new Object[0][]);
}
 
Example 16
@DataProvider(name = "IntStream.limit")
public static Object[][] intSliceFunctionsDataProvider() {
    Function<String, String> f = s -> String.format(s, SKIP_LIMIT_SIZE);

    List<Object[]> data = new ArrayList<>();

    data.add(new Object[]{f.apply("IntStream.limit(%d)"),
            (UnaryOperator<IntStream>) s -> s.limit(SKIP_LIMIT_SIZE)});
    data.add(new Object[]{f.apply("IntStream.skip(%1$d).limit(%1$d)"),
            (UnaryOperator<IntStream>) s -> s.skip(SKIP_LIMIT_SIZE).limit(SKIP_LIMIT_SIZE)});

    return data.toArray(new Object[0][]);
}
 
Example 17
@Test(dataProvider = "DoubleStream.limit")
public void testDoubleUnorderedGenerator(String description, UnaryOperator<DoubleStream> fs) {
    // Source is spliterator of infinite size
    TestData.OfDouble generator = TestData.Factory.ofDoubleSupplier(
            "[1.0, 1.0, ...]", () -> DoubleStream.generate(() -> 1.0));

    withData(generator).
            stream(s -> fs.apply(s.filter(i -> true).unordered())).
            exercise();
}
 
Example 18
private static <T, S extends Spliterator<T>> void testMixedTryAdvanceForEach(
        Collection<T> exp,
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    S spliterator = supplier.get();
    long sizeIfKnown = spliterator.getExactSizeIfKnown();
    boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);

    // tryAdvance first few elements, then forEach rest
    ArrayList<T> dest = new ArrayList<>();
    spliterator = supplier.get();
    Consumer<T> addToDest = boxingAdapter.apply(dest::add);
    for (int i = 0; i < 10 && spliterator.tryAdvance(addToDest); i++) { }
    spliterator.forEachRemaining(addToDest);

    // Assert that forEach now produces no elements
    spliterator.forEachRemaining(boxingAdapter.apply(e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
    // Assert that tryAdvance now produce no elements
    spliterator.tryAdvance(boxingAdapter.apply(e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));

    if (sizeIfKnown >= 0) {
        assertEquals(sizeIfKnown, dest.size());
    }
    assertEquals(dest.size(), exp.size());

    if (isOrdered) {
        assertEquals(dest, exp);
    }
    else {
        assertContentsUnordered(dest, exp);
    }
}
 
Example 19
@DataProvider(name = "DoubleStream.limit")
public static Object[][] doubleSliceFunctionsDataProvider() {
    Function<String, String> f = s -> String.format(s, SKIP_LIMIT_SIZE);

    List<Object[]> data = new ArrayList<>();

    data.add(new Object[]{f.apply("DoubleStream.limit(%d)"),
            (UnaryOperator<DoubleStream>) s -> s.limit(SKIP_LIMIT_SIZE)});
    data.add(new Object[]{f.apply("DoubleStream.skip(%1$d).limit(%1$d)"),
            (UnaryOperator<DoubleStream>) s -> s.skip(SKIP_LIMIT_SIZE).limit(SKIP_LIMIT_SIZE)});

    return data.toArray(new Object[0][]);
}
 
Example 20
@SuppressWarnings({"rawtypes", "unchecked"})
@Test(dataProvider = "StreamTestData<Integer>.mini", dataProviderClass = StreamTestDataProvider.class)
public void testMixedSeqPar(String name, TestData.OfRef<Integer> data) {
    Function<Integer, Integer> id = LambdaTestHelpers.identity();
    UnaryOperator<Stream<Integer>>[] changers
            = new UnaryOperator[] {
            (UnaryOperator<Stream<Integer>>) s -> s,
            (UnaryOperator<Stream<Integer>>) s -> s.sequential(),
            (UnaryOperator<Stream<Integer>>) s -> s.parallel(),
            (UnaryOperator<Stream<Integer>>) s -> s.unordered()
    };
    UnaryOperator<Stream<Integer>>[] stuff
            = new UnaryOperator[] {
            (UnaryOperator<Stream<Integer>>) s -> s,
            (UnaryOperator<Stream<Integer>>) s -> s.map(id),
            (UnaryOperator<Stream<Integer>>) s -> s.sorted(Comparator.naturalOrder()),
            (UnaryOperator<Stream<Integer>>) s -> s.map(id).sorted(Comparator.naturalOrder()).map(id),
            (UnaryOperator<Stream<Integer>>) s -> s.filter(LambdaTestHelpers.pEven).sorted(Comparator.naturalOrder()).map(id),
    };

    for (int c1Index = 0; c1Index < changers.length; c1Index++) {
        setContext("c1Index", c1Index);
        UnaryOperator<Stream<Integer>> c1 = changers[c1Index];
        for (int s1Index = 0; s1Index < stuff.length; s1Index++) {
            setContext("s1Index", s1Index);
            UnaryOperator<Stream<Integer>> s1 = stuff[s1Index];
            for (int c2Index = 0; c2Index < changers.length; c2Index++) {
                setContext("c2Index", c2Index);
                UnaryOperator<Stream<Integer>> c2 = changers[c2Index];
                for (int s2Index = 0; s2Index < stuff.length; s2Index++) {
                    setContext("s2Index", s2Index);
                    UnaryOperator<Stream<Integer>> s2 = stuff[s2Index];
                    UnaryOperator<Stream<Integer>> composed = s -> s2.apply(c2.apply(s1.apply(c1.apply(s))));
                    exerciseOps(data, composed);
                }
            }
        }
    }
}
 
Example 21
@Test(dataProvider = "DoubleStream.limit")
public void testDoubleUnorderedGenerator(String description, UnaryOperator<DoubleStream> fs) {
    // Source is spliterator of infinite size
    TestData.OfDouble generator = TestData.Factory.ofDoubleSupplier(
            "[1.0, 1.0, ...]", () -> DoubleStream.generate(() -> 1.0));

    withData(generator).
            stream(s -> fs.apply(s.filter(i -> true).unordered())).
            exercise();
}
 
Example 22
private static <T, S extends Spliterator<T>> void testMixedTryAdvanceForEach(
        Collection<T> exp,
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    S spliterator = supplier.get();
    long sizeIfKnown = spliterator.getExactSizeIfKnown();
    boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);

    // tryAdvance first few elements, then forEach rest
    ArrayList<T> dest = new ArrayList<>();
    spliterator = supplier.get();
    Consumer<T> addToDest = boxingAdapter.apply(dest::add);
    for (int i = 0; i < 10 && spliterator.tryAdvance(addToDest); i++) { }
    spliterator.forEachRemaining(addToDest);

    // Assert that forEach now produces no elements
    spliterator.forEachRemaining(boxingAdapter.apply(e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
    // Assert that tryAdvance now produce no elements
    spliterator.tryAdvance(boxingAdapter.apply(e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));

    if (sizeIfKnown >= 0) {
        assertEquals(sizeIfKnown, dest.size());
    }
    assertEquals(dest.size(), exp.size());

    if (isOrdered) {
        assertEquals(dest, exp);
    }
    else {
        assertContentsUnordered(dest, exp);
    }
}
 
Example 23
@Test(dataProvider = "LongStream.limit")
public void testLongUnorderedIteration(String description, UnaryOperator<LongStream> fs) {
    // Source is a right-balanced tree of infinite size
    TestData.OfLong iterator = TestData.Factory.ofLongSupplier(
            "[1L, 2L, 3L, ...]", () -> LongStream.iterate(1, i -> i + 1));

    // Ref
    withData(iterator).
            stream(s -> fs.apply(s.unordered())).
            resultAsserter(unorderedAsserter()).
            exercise();
}
 
Example 24
Source Project: jkube   Source File: AuthConfigFactory.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private AuthConfig getAuthConfigFromPluginConfiguration(LookupMode lookupMode, Map<String, ?> authConfig, UnaryOperator<String> passwordDecryptionMethod) {
    Map<String, String> mapToCheck = getAuthConfigMapToCheck(lookupMode,authConfig);

    if (mapToCheck != null && mapToCheck.containsKey(AUTH_USERNAME)) {
        if (!mapToCheck.containsKey(AUTH_PASSWORD)) {
            throw new IllegalStateException("No 'password' given while using <authConfig> in configuration for mode " + lookupMode);
        }
        Map<String, String> cloneConfig = new HashMap<>(mapToCheck);
        cloneConfig.put(AUTH_PASSWORD, passwordDecryptionMethod.apply(cloneConfig.get(AUTH_PASSWORD)));
        return AuthConfig.fromMap(cloneConfig);
    } else {
        return null;
    }
}
 
Example 25
Source Project: gadtry   Source File: ComparatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void Java8TypeIntersectionTest()
{
    UnaryOperator<Integer> func = makeComparator();
    Assert.assertEquals(func.apply(1).intValue(), 2);
    Assert.assertTrue(func instanceof Serializable);
}
 
Example 26
@Test(dataProvider = "Stream.limit")
public void testUnorderedIteration(String description, UnaryOperator<Stream<Long>> fs) {
    // Source is a right-balanced tree of infinite size
    TestData.OfRef<Long> iterator = TestData.Factory.ofSupplier(
            "[1L, 2L, 3L, ...]", () -> Stream.iterate(1L, i -> i + 1L));

    // Ref
    withData(iterator).
            stream(s -> fs.apply(s.unordered())).
            resultAsserter(unorderedAsserter()).
            exercise();
}
 
Example 27
@Test(dataProvider = "DoubleStream.limit")
public void testDoubleUnorderedSizedNotSubsizedFinite(String description, UnaryOperator<DoubleStream> fs) {
    // Range is [0, Double.MAX_VALUE), splits are not SUBSIZED (proxy clears
    // the SUBSIZED characteristic)
    // Such a size will induce out of memory errors for incorrect
    // slice implementations
    withData(proxiedLongRange(0, 1L << 53)).
            stream(s -> fs.apply(s.unordered().mapToDouble(i -> (double) i))).
            resultAsserter(unorderedAsserter()).
            exercise();
}
 
Example 28
Source Project: consulo   Source File: FileLocalStringEnumerator.java    License: Apache License 2.0 5 votes vote down vote up
static void readEnumeratedStrings(@Nonnull FileLocalStringEnumerator enumerator, @Nonnull DataInput stream, @Nonnull UnaryOperator<String> interner) throws IOException {
  final int numberOfStrings = DataInputOutputUtil.readINT(stream);
  byte[] buffer = IOUtil.allocReadWriteUTFBuffer();
  enumerator.myStrings.ensureCapacity(numberOfStrings);

  int i = 0;
  while (i < numberOfStrings) {
    String s = interner.apply(IOUtil.readUTFFast(buffer, stream));
    enumerator.myStrings.add(s);
    ++i;
  }
}
 
Example 29
Source Project: immutables   Source File: CriteriaContext.java    License: Apache License 2.0 5 votes vote down vote up
<R> R applyAndCreateRoot(UnaryOperator<Expression> fn, Combiner nextCombiner) {
  Expression newPartial = fn.apply(state.partial());
  Expression newExpression = state.combiner().combine(state.current(), newPartial);

  // use initial creator
  CriteriaCreator<?> creator = first().state.creator();

  ImmutableState newState = state.withCombiner(nextCombiner)
          .withCreator(creator)
          .withCurrent(newExpression)
          .withPartial(state.defaultPartial());

  return new CriteriaContext(null, newState).create();
}
 
Example 30
private static <T, S extends Spliterator<T>> void testMixedTryAdvanceForEach(
        Collection<T> exp,
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    S spliterator = supplier.get();
    long sizeIfKnown = spliterator.getExactSizeIfKnown();
    boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);

    // tryAdvance first few elements, then forEach rest
    ArrayList<T> dest = new ArrayList<>();
    spliterator = supplier.get();
    Consumer<T> addToDest = boxingAdapter.apply(dest::add);
    for (int i = 0; i < 10 && spliterator.tryAdvance(addToDest); i++) { }
    spliterator.forEachRemaining(addToDest);

    // Assert that forEach now produces no elements
    spliterator.forEachRemaining(boxingAdapter.apply(e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
    // Assert that tryAdvance now produce no elements
    spliterator.tryAdvance(boxingAdapter.apply(e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));

    if (sizeIfKnown >= 0) {
        assertEquals(sizeIfKnown, dest.size());
    }
    assertEquals(dest.size(), exp.size());

    if (isOrdered) {
        assertEquals(dest, exp);
    }
    else {
        assertContentsUnordered(dest, exp);
    }
}