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(); } }
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))); } }
@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)); } })); }
/** * 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()); }
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); } }
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()); }
public static <T> Set<T> load( Function<Model, Set<Resource>> resourceSelector, Class<T> clazz, Repository repository, String sparqlQuery, UnaryOperator<Model> modelAdapter ) { requireNonNull(repository, REPOSITORY_MSG); requireNonNull(sparqlQuery, SPARQL_QUERY_MSG); Model model = QueryUtils.getModelFromRepo(repository, sparqlQuery); return load(resourceSelector, clazz, model, modelAdapter, c -> {}, m -> {}); }
@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>"; }
/** * 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); }
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); }
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; }
@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(); }
@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(); } }
@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(); }
@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(); }
/** * 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(); }
@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); } } } } }
/** * See <a href="http://www.wolframalpha.com/input/?i=integral+of+H+*+e%5E(-1*((A*t%2BB)%5E2%2B(C*t%2BD)%5E2))dt"> * this equation</a>, where <code>x = A*t + B</code> and <code>y = C*t + D</code>. * * @param lowerBound The lower bound of the integral. * @param upperBound The upper bound of the integral. * @return A {@link UnaryOperator} representing the result of the indefinite integral for * which the value can be computed. */ @Override public UnaryOperator<Double> computeLineIntegral( final INDArray lowerBound, final INDArray upperBound ) { return input -> { // compute parametric coefficients final double A = upperBound.getDouble(0, 0) - lowerBound.getDouble(0, 0); final double B = lowerBound.getDouble(0, 0); final double C = upperBound.getDouble(1, 0) - lowerBound.getDouble(1, 0); final double D = lowerBound.getDouble(1, 0); // compute leading coefficients final double coeff = this.height * Math.sqrt(Math.PI) / (2 * Math.sqrt(Math.pow(A, 2) + Math.pow(C, 2))); // compute exponential expression final double eTerm = Math.exp( -1 * Math.pow(B * C - A * D, 2) / (Math.pow(A, 2) + Math.pow(C, 2))); // compute erf expression final double erf = GaussianDistribution.erf( Math.pow(A, 2) * input + Math.pow(C, 2) * input + A * B + C * D); // compute unscaled line integral return coeff * eTerm * erf; }; }
/** * @param origin The starting point of the line integral. * @param target The target point of the line integral. * @return The total potential between the supplied origin and target due to the southern boundary * segment. */ private UnaryOperator<Double> computeSouthernLineIntegralSegment( final INDArray origin, final INDArray target ) { return this.computeLineIntegral(this.getWidth() - origin.getDouble(0, 0), this.getWidth() - target.getDouble(0, 0)); }
@Test(dataProvider = "Stream.limit") public void testUnorderedSizedNotSubsizedFinite(String description, UnaryOperator<Stream<Long>> fs) { // Range is [0, Long.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, Long.MAX_VALUE)). stream(s -> fs.apply(s.unordered().boxed())). resultAsserter(unorderedAsserter()). exercise(); }
/** * See <a href="http://www.wolframalpha.com/input/?i=integral+of+1%2F(1+%2B+e%5E(D+-+(A*t+%2B+B)))dt"> * this equation</a>. * * @param origin The starting distance from the boundary. * @param target The target distance from the boundary. * @return The total potential between the supplied origin and target distances from a boundary. */ private UnaryOperator<Double> computeLineIntegral(final double origin, final double target) { if (origin == target) { return input -> 0d; } return input -> Math.log( Math.exp((target - origin) * input + origin) + Math.exp(this.getFieldDisplacement())) / (target - origin); }
public RestController(Settings settings, Set<String> headersToCopy, UnaryOperator<RestHandler> handlerWrapper, NodeClient client, CircuitBreakerService circuitBreakerService) { super(settings); this.headersToCopy = headersToCopy; if (handlerWrapper == null) { handlerWrapper = h -> h; // passthrough if no wrapper set } this.handlerWrapper = handlerWrapper; this.client = client; this.circuitBreakerService = circuitBreakerService; }
@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(); }
@DataProvider(name = "LongStream.limit") public static Object[][] longSliceFunctionsDataProvider() { Function<String, String> f = s -> String.format(s, SKIP_LIMIT_SIZE); List<Object[]> data = new ArrayList<>(); data.add(new Object[]{f.apply("LongStream.limit(%d)"), (UnaryOperator<LongStream>) s -> s.limit(SKIP_LIMIT_SIZE)}); data.add(new Object[]{f.apply("LongStream.skip(%1$d).limit(%1$d)"), (UnaryOperator<LongStream>) s -> s.skip(SKIP_LIMIT_SIZE).limit(SKIP_LIMIT_SIZE)}); return data.toArray(new Object[0][]); }
@FXML public void initialize(URL url, ResourceBundle rb) { UnaryOperator<TextFormatter.Change> filter = c -> { String proposedText = c.getControlNewText(); if (proposedText.matches(".{0,15}")) { return c ; } else { return null ; } }; namePlayer1.setTextFormatter(new TextFormatter<String>(filter)); namePlayer2.setTextFormatter(new TextFormatter<String>(filter)); }
@Test public void testUnaryOP() { UnaryOperator<Integer> intOperant = (i) -> { return i * i; }; Integer expected = 16; assertEquals(expected, intOperant.apply(4)); }
@Test(dataProvider = "Stream.limit") public void testUnorderedGenerator(String description, UnaryOperator<Stream<Long>> fs) { // Source is spliterator of infinite size TestData.OfRef<Long> generator = TestData.Factory.ofSupplier( "[1L, 1L, ...]", () -> Stream.generate(() -> 1L)); withData(generator). stream(s -> fs.apply(s.filter(i -> true).unordered())). exercise(); }
@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++; }
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); } }
@Test(dataProvider = "LongStream.limit") public void testLongUnorderedGenerator(String description, UnaryOperator<LongStream> fs) { // Source is spliterator of infinite size TestData.OfLong generator = TestData.Factory.ofLongSupplier( "[1L, 1L, ...]", () -> LongStream.generate(() -> 1)); withData(generator). stream(s -> fs.apply(s.filter(i -> true).unordered())). exercise(); }
@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(); }
@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++; }
@Test(dataProvider = "LongStream.limit") public void testLongUnorderedFinite(String description, UnaryOperator<LongStream> fs) { // Range is [0, Long.MAX_VALUE), splits are SUBSIZED // Such a size will induce out of memory errors for incorrect // slice implementations withData(longs()). stream(s -> fs.apply(s.filter(i -> true).unordered())). resultAsserter(unorderedAsserter()). exercise(); }
/** * @throws NullPointerException {@inheritDoc} */ @Override public synchronized void replaceAll(UnaryOperator<E> operator) { Objects.requireNonNull(operator); final int expectedModCount = modCount; final Object[] es = elementData; final int size = elementCount; for (int i = 0; modCount == expectedModCount && i < size; i++) es[i] = operator.apply(elementAt(es, i)); if (modCount != expectedModCount) throw new ConcurrentModificationException(); modCount++; }
@Test(dataProvider = "Stream.limit") public void testSubsizedWithRange(String description, UnaryOperator<Stream<Long>> fs) { // Range is [0, Long.MAX_VALUE), splits are SUBSIZED // Such a size will induce out of memory errors for incorrect // slice implementations withData(refLongs()). stream(s -> fs.apply(s)). without(StreamTestScenario.CLEAR_SIZED_SCENARIOS). exercise(); }
@Test(dataProvider = "DoubleStream.limit") public void testDoubleUnorderedFinite(String description, UnaryOperator<DoubleStream> fs) { // Range is [0, 1L << 53), splits are SUBSIZED // Such a size will induce out of memory errors for incorrect // slice implementations // Upper bound ensures values mapped to doubles will be unique withData(doubles()). stream(s -> fs.apply(s.filter(i -> true).unordered())). resultAsserter(unorderedAsserter()). exercise(); }
@Override public void replaceAll(UnaryOperator<T> operator) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { super.replaceAll(operator); updateSpec = new UpdateSpec(UpdateSpec.UpdateType.ITEM_CHANGED, 0, size(), systemTimeWrapper); } else { throw new UnsupportedOperationException("Not supported by this class"); } }
@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(); }