java.util.function.UnaryOperator Java Examples

The following examples show how to use java.util.function.UnaryOperator. 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
Source File: IPAddress.java    From IPAddress with 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 #2
Source File: SpliteratorCollisions.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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 #3
Source File: Stream.java    From jdk1.8-source-analysis with 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 #4
Source File: SpliteratorCollisions.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 #5
Source File: RngDataOutputTest.java    From commons-rng with 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 #6
Source File: CopyOnWriteArrayList.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 #7
Source File: SpliteratorTraversingAndSplittingTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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 #8
Source File: SpliteratorTraversingAndSplittingTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 #9
Source File: AffineTransformMatrix3DTest.java    From commons-geometry with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: ValidatingSpliteratorTest.java    From streams-utils with 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 #11
Source File: SpliteratorTraversingAndSplittingTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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 #12
Source File: SpliteratorCollisions.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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 #13
Source File: SpliteratorCollisions.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 #14
Source File: InfiniteStreamWithLimitOpTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@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 #15
Source File: SingletonTest.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Override
public <T> IterableX<T> iterate(int times, T seed, UnaryOperator<T> fn) {
    Chain<T> res = null;
    for(T next : ReactiveSeq.<T>iterate(seed,fn).take(times)){
        if(res==null)
            res = Chain.singleton(next);
        else
            res = res.append(next);
    }
    if(res==null)
        return empty();
    return res;
}
 
Example #16
Source File: InfiniteStreamWithLimitOpTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@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
Source File: InfiniteStreamWithLimitOpTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@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 #18
Source File: PublisherBufferConcurrencyTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private void runTest(final UnaryOperator<Publisher<Integer>> beforeBuffer,
                     final UnaryOperator<Publisher<Iterable<Integer>>> afterBuffer) throws Exception {
    final int maxRange = 1000;
    final int repeatMax = 100;
    final Executor executor = executorRule.executor();
    Publisher<Integer> original = Publisher.range(0, maxRange)
            .repeatWhen(count -> count == repeatMax ? failed(DELIBERATE_EXCEPTION) :
                    executor.timer(ofMillis(1)));

    Publisher<Iterable<Integer>> buffered = beforeBuffer.apply(original)
            .buffer(BufferStrategies.forCountOrTime(maxRange / 20, ofMillis(500)));

    afterBuffer.apply(buffered).beforeOnNext(new Consumer<Iterable<Integer>>() {
        private int lastValue = -1;

        @Override
        public void accept(final Iterable<Integer> ints) {
            for (Integer anInt : ints) {
                assertThat("Unexpected value", anInt, greaterThan(lastValue));
                lastValue = anInt == (maxRange - 1) ? -1 : anInt;
            }
        }
    })
            .ignoreElements()
            .toFuture()
            .get();
}
 
Example #19
Source File: SpliteratorTraversingAndSplittingTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
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 #20
Source File: InfiniteStreamWithLimitOpTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@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 #21
Source File: InfiniteStreamWithLimitOpTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "IntStream.limit")
public void testIntUnorderedIteration(String description, UnaryOperator<IntStream> fs) {
    // Source is a right-balanced tree of infinite size
    TestData.OfInt iterator = TestData.Factory.ofIntSupplier(
            "[1, 2, 3, ...]", () -> IntStream.iterate(1, i -> i + 1));

    // Ref
    withData(iterator).
            stream(s -> fs.apply(s.unordered())).
            resultAsserter(unorderedAsserter()).
            exercise();
}
 
Example #22
Source File: Matchers.java    From immutables with Apache License 2.0 5 votes vote down vote up
static <C> UnaryOperator<Expression> toInnerExpression(CriteriaContext context, UnaryOperator<C> expr) {
  return expression -> {
    final CriteriaContext newContext = context.nested();
    @SuppressWarnings("unchecked")
    final C initial = (C) newContext.creator().create(newContext);
    final C changed = expr.apply(initial);
    return Matchers.extract((Matcher) changed).expression();
  };
}
 
Example #23
Source File: SpliteratorCollisions.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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 #24
Source File: CriteriaContext.java    From immutables with 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 #25
Source File: SackStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private SackStrategy(final Supplier initialValue, final UnaryOperator splitOperator, final BinaryOperator mergeOperator) {
    if (null == initialValue)
        throw new IllegalArgumentException("The initial value of a sack can not be null");
    this.initialValue = initialValue;
    this.splitOperator = splitOperator;
    this.mergeOperator = mergeOperator;
}
 
Example #26
Source File: InfiniteStreamWithLimitOpTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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 #27
Source File: ArrayList.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void replaceAll(UnaryOperator<E> operator) {
    Objects.requireNonNull(operator);
    final int expectedModCount = modCount;
    final int size = this.size;
    for (int i=0; modCount == expectedModCount && i < size; i++) {
        elementData[i] = operator.apply((E) elementData[i]);
    }
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}
 
Example #28
Source File: SpliteratorTraversingAndSplittingTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
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 #29
Source File: FileLocalStringEnumerator.java    From consulo with 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 #30
Source File: SequentialOpTest.java    From jdk8u-jdk with 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);
                }
            }
        }
    }
}