public void testIntMethods() { BinaryOperator<Integer> sum1 = Integer::sum; IntBinaryOperator sum2 = Integer::sum; BinaryOperator<Integer> max1 = Integer::max; IntBinaryOperator max2 = Integer::max; BinaryOperator<Integer> min1 = Integer::min; IntBinaryOperator min2 = Integer::min; Comparator<Integer> cmp = Integer::compare; int[] numbers = { -1, 0, 1, 100, Integer.MAX_VALUE, Integer.MIN_VALUE }; for (int i : numbers) { for (int j : numbers) { assertEquals(i+j, (int) sum1.apply(i, j)); assertEquals(i+j, sum2.applyAsInt(i, j)); assertEquals(Math.max(i,j), (int) max1.apply(i, j)); assertEquals(Math.max(i,j), max2.applyAsInt(i, j)); assertEquals(Math.min(i,j), (int) min1.apply(i, j)); assertEquals(Math.min(i,j), min2.applyAsInt(i, j)); assertEquals(((Integer) i).compareTo(j), cmp.compare(i, j)); } } }
public void testLongMethods() { BinaryOperator<Long> sum1 = Long::sum; LongBinaryOperator sum2 = Long::sum; BinaryOperator<Long> max1 = Long::max; LongBinaryOperator max2 = Long::max; BinaryOperator<Long> min1 = Long::min; LongBinaryOperator min2 = Long::min; Comparator<Long> cmp = Long::compare; long[] numbers = { -1, 0, 1, 100, Long.MAX_VALUE, Long.MIN_VALUE }; for (long i : numbers) { for (long j : numbers) { assertEquals(i+j, (long) sum1.apply(i, j)); assertEquals(i+j, sum2.applyAsLong(i, j)); assertEquals(Math.max(i,j), (long) max1.apply(i, j)); assertEquals(Math.max(i,j), max2.applyAsLong(i, j)); assertEquals(Math.min(i,j), (long) min1.apply(i, j)); assertEquals(Math.min(i,j), min2.applyAsLong(i, j)); assertEquals(((Long) i).compareTo(j), cmp.compare(i, j)); } } }
public static <S, T> void solve( Collection<? extends ProblemNeighborhoodAware<S, T>> problems, S baseSolution, Function<? super S, ? extends Collection<T>> getRelatedSources, BinaryOperator<S> solutionCombiner, Predicate<S> isUnsatisfiable, Consumer<S> solutionCallback) { ProblemContainerNeighbourhoodAware<S, T> result = new ProblemContainerNeighbourhoodAware<>( getRelatedSources, solutionCombiner, isUnsatisfiable, solutionCallback ); for(ProblemNeighborhoodAware<S, T> problem : problems) { result.addToRegularQueue(problem); } result.run(baseSolution); //return result; }
/** * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSortedMap} whose * keys and values are the result of applying the provided mapping functions to the input * elements. * * <p>If the mapped keys contain duplicates (according to the comparator), the the values are * merged using the specified merging function. Entries will appear in the encounter order of the * first occurrence of the key. * * @since 21.0 */ @Beta public static <T, K, V> Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap( Comparator<? super K> comparator, Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends V> valueFunction, BinaryOperator<V> mergeFunction) { checkNotNull(comparator); checkNotNull(keyFunction); checkNotNull(valueFunction); checkNotNull(mergeFunction); return Collectors.collectingAndThen( Collectors.toMap( keyFunction, valueFunction, mergeFunction, () -> new TreeMap<K, V>(comparator)), ImmutableSortedMap::copyOfSorted); }
/** * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys * and values are the result of applying the provided mapping functions to the input elements. The * resulting implementation is specialized for enum key types. The returned map and its views will * iterate over keys in their enum definition order, not encounter order. * * <p>If the mapped keys contain duplicates, the values are merged using the specified merging * function. * * @since 21.0 */ @Beta public static <T, K extends Enum<K>, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap( java.util.function.Function<? super T, ? extends K> keyFunction, java.util.function.Function<? super T, ? extends V> valueFunction, BinaryOperator<V> mergeFunction) { checkNotNull(keyFunction); checkNotNull(valueFunction); checkNotNull(mergeFunction); // not UNORDERED because we don't know if mergeFunction is commutative return Collector.of( () -> new Accumulator<K, V>(mergeFunction), (accum, t) -> { K key = checkNotNull(keyFunction.apply(t), "Null key for input %s", t); V newValue = checkNotNull(valueFunction.apply(t), "Null value for input %s", t); accum.put(key, newValue); }, Accumulator::combine, Accumulator::toImmutableMap); }
public void testFloatMethods() { BinaryOperator<Float> sum1 = Float::sum; BinaryOperator<Float> max1 = Float::max; BinaryOperator<Float> min1 = Float::min; Comparator<Float> cmp = Float::compare; float[] numbers = { -1, 0, 1, 100, Float.MAX_VALUE, Float.MIN_VALUE }; for (float i : numbers) { for (float j : numbers) { assertEquals(i+j, (float) sum1.apply(i, j)); assertEquals(Math.max(i,j), (float) max1.apply(i, j)); assertEquals(Math.min(i,j), (float) min1.apply(i, j)); assertEquals(((Float) i).compareTo(j), cmp.compare(i, j)); } } }
/** * Returns a new {@code Collector} described by the given {@code supplier}, * {@code accumulator}, {@code combiner}, and {@code finisher} functions. * * @param supplier The supplier function for the new collector * @param accumulator The accumulator function for the new collector * @param combiner The combiner function for the new collector * @param finisher The finisher function for the new collector * @param characteristics The collector characteristics for the new * collector * @param <T> The type of input elements for the new collector * @param <A> The intermediate accumulation type of the new collector * @param <R> The final result type of the new collector * @throws NullPointerException if any argument is null * @return the new {@code Collector} */ public static<T, A, R> Collector<T, A, R> of(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner, Function<A, R> finisher, Characteristics... characteristics) { Objects.requireNonNull(supplier); Objects.requireNonNull(accumulator); Objects.requireNonNull(combiner); Objects.requireNonNull(finisher); Objects.requireNonNull(characteristics); Set<Characteristics> cs = Collectors.CH_NOID; if (characteristics.length > 0) { cs = EnumSet.noneOf(Characteristics.class); Collections.addAll(cs, characteristics); cs = Collections.unmodifiableSet(cs); } return new Collectors.CollectorImpl<>(supplier, accumulator, combiner, finisher, cs); }
/** * Constructs a {@code TerminalOp} that implements a mutable reduce on * reference values. * * @param <T> the type of the input elements * @param <I> the type of the intermediate reduction result * @param collector a {@code Collector} defining the reduction * @return a {@code ReduceOp} implementing the reduction */ public static <T, I> TerminalOp<T, I> makeRef(Collector<? super T, I, ?> collector) { Supplier<I> supplier = Objects.requireNonNull(collector).supplier(); BiConsumer<I, ? super T> accumulator = collector.accumulator(); BinaryOperator<I> combiner = collector.combiner(); class ReducingSink extends Box<I> implements AccumulatingSink<T, I, ReducingSink> { @Override public void begin(long size) { state = supplier.get(); } @Override public void accept(T t) { accumulator.accept(state, t); } @Override public void combine(ReducingSink other) { state = combiner.apply(state, other.state); } } return new ReduceOp<T, I, ReducingSink>(StreamShape.REFERENCE) { @Override public ReducingSink makeSink() { return new ReducingSink(); } @Override public int getOpFlags() { return collector.characteristics().contains(Collector.Characteristics.UNORDERED) ? StreamOpFlag.NOT_ORDERED : 0; } }; }
public static <T extends Unit> Collector<T, Group<T>, Group<T>> toGroup() { return new Collector<T, Group<T>, Group<T>>(){ @Override public Supplier<Group<T>> supplier() { return (Supplier<Group<T>>) Group::new; } @Override public BiConsumer<Group<T>, T> accumulator() { return (group, value) -> group.add(value); } @Override public BinaryOperator<Group<T>> combiner() { return (left, right) -> { left.addAll(right); return left; }; } @Override public Function<Group<T>, Group<T>> finisher() { return Function.identity(); } @Override public Set<Characteristics> characteristics() { return Collections.singleton(Characteristics.IDENTITY_FINISH); } }; }
@Override public BinaryOperator<Map<String, JsonArray>> combiner() { return (m1, m2) -> Stream.concat(m1.entrySet().stream(), m2.entrySet().stream()) .collect(Collectors.groupingBy(Map.Entry::getKey, HashMap::new, Collector.of(JsonArray::new, (arr, e) -> arr.addAll(e.getValue()), JsonArray::addAll))); }
@Override public BinaryOperator<List<Integer>> combiner() { return (a, b) -> { a.addAll(b); return a; }; }
/** * Ctor. * * @param combineOperator Combination function * @param defaultValue a value for default result * @param results Results to combine */ public RCombinedOrDefault(BinaryOperator<T> combineOperator, T defaultValue, List<Result<T>> results) { this( combineOperator, new RSuccess<>(defaultValue), results ); }
@Override public BinaryOperator<Map<K, List<T>>> combiner() { return (left, right) -> { right.forEach((key, value) -> { left.merge(key, value, (leftValue, rightValue) -> { leftValue.addAll(rightValue); return leftValue; }); }); return left; }; }
/** * Ctor. * * @param combineOperator Combination function * @param defaultValue a value for default result * @param results Results to combine */ public RCombinedOrDefault(BinaryOperator<T> combineOperator, T defaultValue, Result<T>... results) { this( combineOperator, defaultValue, List.of(results) ); }
/** * Constructs a {@code TerminalOp} that implements a mutable reduce on * {@code int} values. * * @param <R> The type of the result * @param supplier a factory to produce a new accumulator of the result type * @param accumulator a function to incorporate an int into an * accumulator * @param combiner a function to combine an accumulator into another * @return A {@code ReduceOp} implementing the reduction */ public static <R> TerminalOp<Integer, R> makeInt(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BinaryOperator<R> combiner) { Objects.requireNonNull(supplier); Objects.requireNonNull(accumulator); Objects.requireNonNull(combiner); class ReducingSink extends Box<R> implements AccumulatingSink<Integer, R, ReducingSink>, Sink.OfInt { @Override public void begin(long size) { state = supplier.get(); } @Override public void accept(int t) { accumulator.accept(state, t); } @Override public void combine(ReducingSink other) { state = combiner.apply(state, other.state); } } return new ReduceOp<Integer, R, ReducingSink>(StreamShape.INT_VALUE) { @Override public ReducingSink makeSink() { return new ReducingSink(); } }; }
@Test public void testBinaryOp() { BinaryOperator<Float> floatBiOperand = (f, g) -> { return f * g; }; float expectedFloat = 84F; assertEquals(expectedFloat, floatBiOperand.apply(7F, 12F), 0.1); }
@Override public BinaryOperator<Pair<List<L>, List<R>>> combiner() { return (x, y) -> Pair.of( Stream.of(x, y).flatMap(l -> l.left.stream()).collect(toList()), Stream.of(x, y).flatMap(r -> r.right.stream()).collect(toList()) ); }
@Override public final <R> R collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner) { BinaryOperator<R> operator = (left, right) -> { combiner.accept(left, right); return left; }; return evaluate(ReduceOps.makeInt(supplier, accumulator, operator)); }
/** Subtask constructor */ CumulateTask(CumulateTask<T> parent, BinaryOperator<T> function, T[] array, int origin, int fence, int threshold, int lo, int hi) { super(parent); this.function = function; this.array = array; this.origin = origin; this.fence = fence; this.threshold = threshold; this.lo = lo; this.hi = hi; }
void put(R row, C column, V value, BinaryOperator<V> merger) { MutableCell<R, C, V> oldCell = table.get(row, column); if (oldCell == null) { MutableCell<R, C, V> cell = new MutableCell<>(row, column, value); insertionOrder.add(cell); table.put(row, column, cell); } else { oldCell.merge(value, merger); } }
@DataProvider(name = "stringSet") public static Object[][] stringSet(){ Function<Integer, String[]> stringsFunc = size -> IntStream.range(0, size).mapToObj(Integer::toString).toArray(String[]::new); BinaryOperator<String> concat = String::concat; return genericData(stringsFunc, (BinaryOperator<String>[]) new BinaryOperator[]{ concat }); }
@Override public final <R> R collect(Supplier<R> supplier, ObjLongConsumer<R> accumulator, BiConsumer<R, R> combiner) { Objects.requireNonNull(combiner); BinaryOperator<R> operator = (left, right) -> { combiner.accept(left, right); return left; }; return evaluate(ReduceOps.makeLong(supplier, accumulator, operator)); }
/** Root task constructor */ public CumulateTask(CumulateTask<T> parent, BinaryOperator<T> function, T[] array, int lo, int hi) { super(parent); this.function = function; this.array = array; this.lo = this.origin = lo; this.hi = this.fence = hi; int p; this.threshold = (p = (hi - lo) / (ForkJoinPool.getCommonPoolParallelism() << 3)) <= MIN_PARTITION ? MIN_PARTITION : p; }
/** * Constructs a {@code TerminalOp} that implements a mutable reduce on * {@code double} values. * * @param <R> the type of the result * @param supplier a factory to produce a new accumulator of the result type * @param accumulator a function to incorporate an int into an * accumulator * @param combiner a function to combine an accumulator into another * @return a {@code TerminalOp} implementing the reduction */ public static <R> TerminalOp<Double, R> makeDouble(Supplier<R> supplier, ObjDoubleConsumer<R> accumulator, BinaryOperator<R> combiner) { Objects.requireNonNull(supplier); Objects.requireNonNull(accumulator); Objects.requireNonNull(combiner); class ReducingSink extends Box<R> implements AccumulatingSink<Double, R, ReducingSink>, Sink.OfDouble { @Override public void begin(long size) { state = supplier.get(); } @Override public void accept(double t) { accumulator.accept(state, t); } @Override public void combine(ReducingSink other) { state = combiner.apply(state, other.state); } } return new ReduceOp<Double, R, ReducingSink>(StreamShape.DOUBLE_VALUE) { @Override public ReducingSink makeSink() { return new ReducingSink(); } }; }
ToMapAssertion(Function<T, K> keyFn, Function<T, V> valueFn, BinaryOperator<V> mergeFn, Class<? extends Map> clazz) { this.clazz = clazz; this.keyFn = keyFn; this.valueFn = valueFn; this.mergeFn = mergeFn; }
@Test(dataProvider="stringSet") public void testParallelPrefixForStringr(String[] data , int fromIndex, int toIndex, BinaryOperator<String> op) { String[] sequentialResult = data.clone(); for (int index = fromIndex + 1; index < toIndex; index++) { sequentialResult[index ] = op.apply(sequentialResult[index - 1], sequentialResult[index]); } String[] parallelResult = data.clone(); Arrays.parallelPrefix(parallelResult, fromIndex, toIndex, op); assertArraysEqual(parallelResult, sequentialResult); String[] parallelRangeResult = Arrays.copyOfRange(data, fromIndex, toIndex); Arrays.parallelPrefix(parallelRangeResult, op); assertArraysEqual(parallelRangeResult, Arrays.copyOfRange(sequentialResult, fromIndex, toIndex)); }
private static <T,K,U,M extends Map<K,U>> Collector<T,M,M> relaxedMapCollector( Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, Supplier<M> supplier){ return new Collector<T,M,M>(){ @Override public Supplier<M> supplier(){ return supplier; } @Override public BiConsumer<M,T> accumulator(){ return (map, element) -> { K key = keyMapper.apply(element); U value = valueMapper.apply(element); map.put(key, value); }; } @Override public BinaryOperator<M> combiner(){ return (map1, map2) -> { map1.putAll(map2); return map1; }; } @Override public Function<M,M> finisher(){ return Function.identity(); } @Override public Set<Collector.Characteristics> characteristics(){ return Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)); } }; }
static Future<JsonObject> findOne(final String collection, final JsonObject filter, final String joinedCollection, final String joinedKey, final JsonObject additional, final BinaryOperator<JsonObject> operatorFun) { final JsonObject data = new JsonObject(); return findOne(collection, filter) .compose(result -> { data.mergeIn(result); final JsonObject joinedFilter = (null == additional) ? new JsonObject() : additional.copy(); // MongoDB only joinedFilter.put(joinedKey, result.getValue("_id")); return findOne(joinedCollection, joinedFilter); }) .compose(second -> Future.succeededFuture(operatorFun.apply(data, second))); }
@Override public BinaryOperator<List<T>> combiner() { return (a, b) -> { a.addAll(b); return a; }; }
public AdaptedBinaryOperator(final BinaryOperator<OT> binaryOperator, final Function<T, OT> inputAdapter, final BiFunction<T, OT, T> outputAdapter) { setBinaryOperator(binaryOperator); setInputAdapter(inputAdapter); setOutputAdapter(outputAdapter); }
@Override public BinaryOperator<Set<Map.Entry<String, byte[]>>> combiner() { return (setOne, setTwo) -> { setOne.addAll(setTwo); return setOne; }; }
/** */ public static <K, V, M extends Map<K, V>> M mergeMaps(M m1, M m2, BinaryOperator<V> op, Supplier<M> mapSupplier) { return Stream.of(m1, m2) .map(Map::entrySet) .flatMap(Collection::stream) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, op, mapSupplier)); }
/** * Constructs a {@code TerminalOp} that implements a functional reduce on * reference values. * * @param <T> the type of the input elements * @param <U> the type of the result * @param seed the identity element for the reduction * @param reducer the accumulating function that incorporates an additional * input element into the result * @param combiner the combining function that combines two intermediate * results * @return a {@code TerminalOp} implementing the reduction */ public static <T, U> TerminalOp<T, U> makeRef(U seed, BiFunction<U, ? super T, U> reducer, BinaryOperator<U> combiner) { Objects.requireNonNull(reducer); Objects.requireNonNull(combiner); class ReducingSink extends Box<U> implements AccumulatingSink<T, U, ReducingSink> { @Override public void begin(long size) { state = seed; } @Override public void accept(T t) { state = reducer.apply(state, t); } @Override public void combine(ReducingSink other) { state = combiner.apply(state, other.state); } } return new ReduceOp<T, U, ReducingSink>(StreamShape.REFERENCE) { @Override public ReducingSink makeSink() { return new ReducingSink(); } }; }
@Override public final <R> R collect(Supplier<R> supplier, ObjLongConsumer<R> accumulator, BiConsumer<R, R> combiner) { BinaryOperator<R> operator = (left, right) -> { combiner.accept(left, right); return left; }; return evaluate(ReduceOps.makeLong(supplier, accumulator, operator)); }
@Override public final <R> R collect(Supplier<R> supplier, ObjDoubleConsumer<R> accumulator, BiConsumer<R, R> combiner) { Objects.requireNonNull(combiner); BinaryOperator<R> operator = (left, right) -> { combiner.accept(left, right); return left; }; return evaluate(ReduceOps.makeDouble(supplier, accumulator, operator)); }
@SafeVarargs public static <K, V> Map<K, V> concat(BinaryOperator<V> resolver, Map<? extends K, ? extends V>... maps) { return Arrays.stream(maps) .flatMap(map -> map.entrySet().stream()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, resolver )); }