本文整理匯總了Java中java.util.function.UnaryOperator類的典型用法代碼示例。如果您正苦於以下問題:Java UnaryOperator類的具體用法?Java UnaryOperator怎麽用?Java UnaryOperator使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
UnaryOperator類屬於java.util.function包,在下文中一共展示了UnaryOperator類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: replaceAll
import java.util.function.UnaryOperator; //導入依賴的package包/類
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();
}
}
示例2: main
import java.util.function.UnaryOperator; //導入依賴的package包/類
public static void main(String[] args) {
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault());
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.');
DecimalFormat df = new DecimalFormat("###0.00", otherSymbols);
List<Double> prices = Arrays.stream(sc.nextLine().split(", "))
.map(Double::parseDouble).collect(Collectors.toList());
UnaryOperator<Double> uOp = (x) -> x * 1.2;
System.out.println("Prices with VAT:");
for(Double price : prices){
System.out.println(df.format(uOp.apply(price)));
}
}
示例3: unaryOperator
import java.util.function.UnaryOperator; //導入依賴的package包/類
@Test
public void unaryOperator()
{
// TODO - Convert the anonymous inner class to a lambda
UnaryOperator<Integer> squared = integer -> integer * integer;
Assert.assertEquals(Integer.valueOf(4), squared.apply(2));
Assert.assertEquals(Integer.valueOf(9), squared.apply(3));
Assert.assertEquals(Integer.valueOf(16), squared.apply(4));
Assert.assertTrue(Stream.iterate(2, squared).anyMatch(new Predicate<Integer>()
{
@Override
public boolean test(Integer i)
{
return i.equals(Integer.valueOf(256));
}
}));
}
示例4: inits
import java.util.function.UnaryOperator; //導入依賴的package包/類
/**
* Builds the initial segments of the given <em>finite</em> input stream
* {@code ts}.
* For example, if {@code ts = [1, 2, 3]} then {@code init(ts) = [[], [1],
* [1,2], [1,2,3]]}.
* This is a terminal operation.
* @param <T> any type.
* @param ts the input stream.
* @return the initial segments of {@code ts}.
* @throws NullPointerException if any argument is {@code null}.
*/
public static <T> Stream<Stream<T>> inits(Stream<T> ts) {
requireNonNull(ts, "ts");
List<T> xs = ts.collect(toList());
Pair<Stream<T>, Long> seed = new Pair<>(empty(), 0L);
UnaryOperator<Pair<Stream<T>, Long>> nextSegment = k -> {
long size = k.snd() + 1;
Stream<T> segment = xs.stream().limit(size);
return new Pair<>(segment, size);
};
return iterate(seed, nextSegment)
.map(Pair::fst)
.limit(1 + xs.size());
}
示例5: testSplitSixDeep
import java.util.function.UnaryOperator; //導入依賴的package包/類
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();
assertRootSpliterator(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);
}
}
示例6: load
import java.util.function.UnaryOperator; //導入依賴的package包/類
public static <T> Set<T> load(
Function<Model, Set<Resource>> resourceSelector,
Class<T> clazz,
Model model,
UnaryOperator<Model> modelAdapter,
Consumer<MappingCache> populateCache,
Consumer<Mapper> configureMapper
) {
requireNonNull(resourceSelector, RESOURCE_SELECTOR_MSG);
requireNonNull(clazz, CLASS_MSG);
requireNonNull(model, MODEL_MSG);
requireNonNull(modelAdapter, MODEL_ADAPTER_MSG);
requireNonNull(populateCache, POPULATE_CACHE_MSG);
MapperImpl mapper = new MapperImpl();
populateCache.accept(mapper);
configureMapper.accept(mapper);
Set<Resource> resources = resourceSelector.apply(model);
return resources
.stream()
.<T> map(r -> mapper.map(modelAdapter.apply(model), r, clazz))
.collect(ImmutableCollectors.toImmutableSet());
}
示例7: render
import java.util.function.UnaryOperator; //導入依賴的package包/類
@Override
public String render(Button model,
UnaryOperator<String> argRes,
RenderService renderer) {
return
"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"btn btn-primary\">\n" +
" <tbody>\n" +
" <tr>\n" +
" <td align=\"left\">\n" +
" <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n" +
" <tbody>\n" +
" <tr>\n" +
" <td> <a href=\"" +
argRes.apply(model.getHref()) + "\" target=\"_blank\">" +
argRes.apply(model.getValue()) + "</a> </td>\n" +
" </tr>\n" +
" </tbody>\n" +
" </table>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody>\n" +
"</table>";
}
示例8: iterate
import java.util.function.UnaryOperator; //導入依賴的package包/類
/**
* 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);
}
示例9: testTryAdvance
import java.util.function.UnaryOperator; //導入依賴的package包/類
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);
}
示例10: encodeMapOfLists
import java.util.function.UnaryOperator; //導入依賴的package包/類
private static Map<String, List<String>> encodeMapOfLists(Map<String, List<String>> map, UnaryOperator<String> encoder) {
Validate.notNull(map, "Map must not be null.");
Map<String, List<String>> result = new LinkedHashMap<>();
for (Entry<String, List<String>> queryParameter : map.entrySet()) {
String key = queryParameter.getKey();
String encodedKey = encoder.apply(key);
List<String> value = queryParameter.getValue();
List<String> encodedValue = value == null
? null
: queryParameter.getValue().stream().map(encoder).collect(Collectors.toList());
result.put(encodedKey, encodedValue);
}
return result;
}
示例11: testDoubleSubsizedWithRange
import java.util.function.UnaryOperator; //導入依賴的package包/類
@Test(dataProvider = "DoubleStream.limit")
public void testDoubleSubsizedWithRange(String description, UnaryOperator<DoubleStream> fs) {
// Range is [0, 2^53), splits are SUBSIZED
// Such a size will induce out of memory errors for incorrect
// slice implementations
withData(doubles()).
stream(s -> fs.apply(s)).
without(DoubleStreamTestScenario.CLEAR_SIZED_SCENARIOS).
exercise();
}
示例12: build
import java.util.function.UnaryOperator; //導入依賴的package包/類
@Override
void build(Path inputFile, Path out) throws Throwable {
try {
R8Command.Builder builder = R8Command.builder();
for (UnaryOperator<R8Command.Builder> transformation : builderTransformations) {
builder = transformation.apply(builder);
}
R8Command command = builder.addProgramFiles(inputFile).setOutputPath(out).build();
ToolHelper.runR8(command, this::combinedOptionConsumer);
} catch (ExecutionException e) {
throw e.getCause();
}
}
示例13: testIntUnorderedSizedNotSubsizedFinite
import java.util.function.UnaryOperator; //導入依賴的package包/類
@Test(dataProvider = "IntStream.limit")
public void testIntUnorderedSizedNotSubsizedFinite(String description, UnaryOperator<IntStream> fs) {
// Range is [0, Integer.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, Integer.MAX_VALUE)).
stream(s -> fs.apply(s.unordered().mapToInt(i -> (int) i))).
resultAsserter(unorderedAsserter()).
exercise();
}
示例14: testLongUnorderedIteration
import java.util.function.UnaryOperator; //導入依賴的package包/類
@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();
}
示例15: computeLineIntegral
import java.util.function.UnaryOperator; //導入依賴的package包/類
/**
* See <a href="http://www.wolframalpha.com/input/?i=integral+of+-S*((a*t%2Bb)*Cos%5BA%5D+%2B+(c*t%2Bd)*Sin%5BA%5D)+wrt+t">this equation.</a>
* @param lowerBound The lower bound of the integral.
* @param upperBound The upper bound of the integral.
* @return A {@link UnaryOperator} representing the indefinite integral of the parametrized line
* integral.
*/
@Override
public UnaryOperator<Double> computeLineIntegral(
final INDArray lowerBound,
final INDArray upperBound
) {
return input ->
upperBound.sub(lowerBound)
.mul(Math.pow(input, 2) / 2d)
.add(lowerBound.mul(input))
.mul(this.multiplier)
.sumNumber().doubleValue();
}