Java Code Examples for java.util.function.UnaryOperator#apply()

The following examples show how to use java.util.function.UnaryOperator#apply() . 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: SpliteratorTraversingAndSplittingTest.java    From jdk8u-dev-jdk 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 2
Source File: Stream.java    From openjdk-jdk9 with GNU General Public License v2.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}.
 *
 * <p>The action of applying {@code f} for one element
 * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>
 * the action of applying {@code f} for subsequent elements.  For any given
 * element the action may be performed in whatever thread the library
 * chooses.
 *
 * @param <T> the type of stream elements
 * @param seed the initial element
 * @param f a function to be applied 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);
    Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE,
           Spliterator.ORDERED | Spliterator.IMMUTABLE) {
        T prev;
        boolean started;

        @Override
        public boolean tryAdvance(Consumer<? super T> action) {
            Objects.requireNonNull(action);
            T t;
            if (started)
                t = f.apply(prev);
            else {
                t = seed;
                started = true;
            }
            action.accept(prev = t);
            return true;
        }
    };
    return StreamSupport.stream(spliterator, false);
}
 
Example 3
Source File: Stream.java    From TencentKona-8 with GNU General Public License v2.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 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: CatnipImpl.java    From catnip with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nonnull
@Override
public Catnip injectOptions(@Nonnull final Extension extension, @Nonnull final UnaryOperator<CatnipOptions> optionsPatcher) {
    if(!extensionManager.matchingExtensions(extension.getClass()).isEmpty()) {
        final CatnipOptions patchedOptions = optionsPatcher.apply((CatnipOptions) options.clone());
        final Map<String, Pair<Object, Object>> diff = diff(patchedOptions);
        if(!diff.isEmpty()) {
            sanityCheckOptions(patchedOptions);
            options = patchedOptions;
            injectSelf();
            if(logExtensionOverrides) {
                diff.forEach((name, patch) -> logAdapter().info("Extension {} updated {} from \"{}\" to \"{}\".",
                        extension.name(), name, patch.getLeft(), patch.getRight()));
            }
        }
    } else {
        throw new IllegalArgumentException("Extension with class " + extension.getClass().getName()
                + " isn't loaded, but tried to inject options!");
    }
    
    return this;
}
 
Example 5
Source File: Vector.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public synchronized void replaceAll(UnaryOperator<E> operator) {
    Objects.requireNonNull(operator);
    final int expectedModCount = modCount;
    final int size = elementCount;
    for (int i=0; modCount == expectedModCount && i < size; i++) {
        elementData[i] = operator.apply((E) elementData[i]);
    }
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}
 
Example 6
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);
                }
            }
        }
    }
}
 
Example 7
Source File: CopyOnWriteArrayList.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void replaceAll(UnaryOperator<E> operator, int i, int end) {
    // assert Thread.holdsLock(lock);
    final Object[] es = getArray().clone();
    for (; i < end; i++)
        es[i] = operator.apply(elementAt(es, i));
    setArray(es);
}
 
Example 8
Source File: SpliteratorCollisions.java    From jdk8u-jdk 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 9
Source File: SpliteratorCollisions.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static <T, S extends Spliterator<T>> void testForEach(
        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> fromForEach = new ArrayList<>();
    spliterator = supplier.get();
    Consumer<T> addToFromForEach = boxingAdapter.apply(fromForEach::add);
    spliterator.forEachRemaining(addToFromForEach);

    // 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());
    }
    if (exp.contains(null)) {
        assertTrue(fromForEach.contains(null));
    }
    assertEquals(fromForEach.size(), exp.size());

    assertContents(fromForEach, exp, isOrdered);
}
 
Example 10
Source File: SourceAnnotator.java    From huntbugs with Apache License 2.0 5 votes vote down vote up
Frame replaceAll(UnaryOperator<Expression> op) {
    Map<Variable, Expression> res = null;
    for (Entry<Variable, Expression> e : sources.entrySet()) {
        Expression expr = op.apply(e.getValue());
        if (expr != e.getValue()) {
            if (res == null)
                res = new IdentityHashMap<>(sources);
            res.put(e.getKey(), expr);
        }
    }
    return res == null ? this : new Frame(this, res, this.fieldValues);
}
 
Example 11
Source File: Vector.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public synchronized void replaceAll(UnaryOperator<E> operator) {
    Objects.requireNonNull(operator);
    final int expectedModCount = modCount;
    final int size = elementCount;
    for (int i=0; modCount == expectedModCount && i < size; i++) {
        elementData[i] = operator.apply((E) elementData[i]);
    }
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}
 
Example 12
Source File: Vector.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public synchronized void replaceAll(UnaryOperator<E> operator) {
    Objects.requireNonNull(operator);
    final int expectedModCount = modCount;
    final int size = elementCount;
    for (int i=0; modCount == expectedModCount && i < size; i++) {
        elementData[i] = operator.apply((E) elementData[i]);
    }
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}
 
Example 13
Source File: ReactiveFetcherDelegate.java    From immutables with Apache License 2.0 4 votes vote down vote up
@Override
public ReactiveFetcher<T> changeQuery(UnaryOperator<Query> mapFn) {
  return new ReactiveFetcherDelegate<>(mapFn.apply(query), session);
}
 
Example 14
Source File: MaxFunction.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public void synchronizeDataCollectors(UnaryOperator<ReductionDataCollector<?>> sync) {
  collector = (DoubleMaxCollector)sync.apply(collector);
}
 
Example 15
Source File: DefaultDittoJsonHandler.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static String getEscapedJsonString(final String javaString) {
    final UnaryOperator<String> javaStringToEscapeJsonString = JavaStringToEscapedJsonString.getInstance();
    return javaStringToEscapeJsonString.apply(javaString);
}
 
Example 16
Source File: AtomicReference.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Atomically updates the current value with the results of
 * applying the given function, returning the updated value. The
 * function should be side-effect-free, since it may be re-applied
 * when attempted updates fail due to contention among threads.
 *
 * @param updateFunction a side-effect-free function
 * @return the updated value
 * @since 1.8
 */
public final V updateAndGet(UnaryOperator<V> updateFunction) {
    V prev, next;
    do {
        prev = get();
        next = updateFunction.apply(prev);
    } while (!compareAndSet(prev, next));
    return next;
}
 
Example 17
Source File: AtomicReferenceArray.java    From TencentKona-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Atomically updates the element at index {@code i} with the results
 * of applying the given function, returning the updated value. The
 * function should be side-effect-free, since it may be re-applied
 * when attempted updates fail due to contention among threads.
 *
 * @param i the index
 * @param updateFunction a side-effect-free function
 * @return the updated value
 * @since 1.8
 */
public final E updateAndGet(int i, UnaryOperator<E> updateFunction) {
    long offset = checkedByteOffset(i);
    E prev, next;
    do {
        prev = getRaw(offset);
        next = updateFunction.apply(prev);
    } while (!compareAndSetRaw(offset, prev, next));
    return next;
}
 
Example 18
Source File: TemporalAdjusters.java    From Java8CN with Apache License 2.0 3 votes vote down vote up
/**
 * Obtains a {@code TemporalAdjuster} that wraps a date adjuster.
 * <p>
 * The {@code TemporalAdjuster} is based on the low level {@code Temporal} interface.
 * This method allows an adjustment from {@code LocalDate} to {@code LocalDate}
 * to be wrapped to match the temporal-based interface.
 * This is provided for convenience to make user-written adjusters simpler.
 * <p>
 * In general, user-written adjusters should be static constants:
 * <pre>{@code
 *  static TemporalAdjuster TWO_DAYS_LATER =
 *       TemporalAdjusters.ofDateAdjuster(date -> date.plusDays(2));
 * }</pre>
 *
 * @param dateBasedAdjuster  the date-based adjuster, not null
 * @return the temporal adjuster wrapping on the date adjuster, not null
 */
public static TemporalAdjuster ofDateAdjuster(UnaryOperator<LocalDate> dateBasedAdjuster) {
    Objects.requireNonNull(dateBasedAdjuster, "dateBasedAdjuster");
    return (temporal) -> {
        LocalDate input = LocalDate.from(temporal);
        LocalDate output = dateBasedAdjuster.apply(input);
        return temporal.with(output);
    };
}
 
Example 19
Source File: AtomicReference.java    From jdk8u_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Atomically updates the current value with the results of
 * applying the given function, returning the updated value. The
 * function should be side-effect-free, since it may be re-applied
 * when attempted updates fail due to contention among threads.
 *
 * @param updateFunction a side-effect-free function
 * @return the updated value
 * @since 1.8
 */
public final V updateAndGet(UnaryOperator<V> updateFunction) {
    V prev, next;
    do {
        prev = get();
        next = updateFunction.apply(prev);
    } while (!compareAndSet(prev, next));
    return next;
}
 
Example 20
Source File: TemporalAdjusters.java    From dragonwell8_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Obtains a {@code TemporalAdjuster} that wraps a date adjuster.
 * <p>
 * The {@code TemporalAdjuster} is based on the low level {@code Temporal} interface.
 * This method allows an adjustment from {@code LocalDate} to {@code LocalDate}
 * to be wrapped to match the temporal-based interface.
 * This is provided for convenience to make user-written adjusters simpler.
 * <p>
 * In general, user-written adjusters should be static constants:
 * <pre>{@code
 *  static TemporalAdjuster TWO_DAYS_LATER =
 *       TemporalAdjusters.ofDateAdjuster(date -> date.plusDays(2));
 * }</pre>
 *
 * @param dateBasedAdjuster  the date-based adjuster, not null
 * @return the temporal adjuster wrapping on the date adjuster, not null
 */
public static TemporalAdjuster ofDateAdjuster(UnaryOperator<LocalDate> dateBasedAdjuster) {
    Objects.requireNonNull(dateBasedAdjuster, "dateBasedAdjuster");
    return (temporal) -> {
        LocalDate input = LocalDate.from(temporal);
        LocalDate output = dateBasedAdjuster.apply(input);
        return temporal.with(output);
    };
}