Java Code Examples for java.util.stream.Stream#reduce()

The following examples show how to use java.util.stream.Stream#reduce() . 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: Params.java    From Alink with Apache License 2.0 6 votes vote down vote up
public <V> V get(ParamInfo <V> paramInfo) {
	Stream <V> paramValue = getParamNameAndAlias(paramInfo)
		.filter(this::contains)
		.map(x -> this.get(x, paramInfo.getValueClass()))
		.limit(1);
	if (paramInfo.isOptional()) {
		if (paramInfo.hasDefaultValue()) {
			return paramValue.reduce(paramInfo.getDefaultValue(), (a, b) -> b);
		} else {
			return paramValue.collect(Collectors.collectingAndThen(Collectors.toList(),
				a -> {
					if (a.isEmpty()) {
						throw new RuntimeException("Not have defaultValue for parameter: " + paramInfo.getName());
					}
					return a.get(0);
				}));
		}
	}
	return paramValue.collect(Collectors.collectingAndThen(Collectors.toList(),
		a -> {
			if (a.isEmpty()) {
				throw new RuntimeException("Not have parameter: " + paramInfo.getName());
			}
			return a.get(0);
		}));
}
 
Example 2
Source File: MapUsingReduce.java    From https-github.com-RichardWarburton-java-8-Lambdas-exercises with MIT License 6 votes vote down vote up
public static <I, O> List<O> map(Stream<I> stream, Function<I, O> mapper) {
    return stream.reduce(new ArrayList<O>(), (acc, x) -> {
    	// We are copying data from acc to new list instance. It is very inefficient,
    	// but contract of Stream.reduce method requires that accumulator function does
    	// not mutate its arguments.
    	// Stream.collect method could be used to implement more efficient mutable reduction,
    	// but this exercise asks to use reduce method.
    	List<O> newAcc = new ArrayList<>(acc);
    	newAcc.add(mapper.apply(x));
        return newAcc;
    }, (List<O> left, List<O> right) -> {
    	// We are copying left to new list to avoid mutating it. 
    	List<O> newLeft = new ArrayList<>(left);
    	newLeft.addAll(right);
        return newLeft;
    });
}
 
Example 3
Source File: MapUsingReduce.java    From java-8-lambdas-exercises with MIT License 6 votes vote down vote up
public static <I, O> List<O> map(Stream<I> stream, Function<I, O> mapper) {
    return stream.reduce(new ArrayList<O>(), (acc, x) -> {
    	// We are copying data from acc to new list instance. It is very inefficient,
    	// but contract of Stream.reduce method requires that accumulator function does
    	// not mutate its arguments.
    	// Stream.collect method could be used to implement more efficient mutable reduction,
    	// but this exercise asks to use reduce method.
    	List<O> newAcc = new ArrayList<>(acc);
    	newAcc.add(mapper.apply(x));
        return newAcc;
    }, (List<O> left, List<O> right) -> {
    	// We are copying left to new list to avoid mutating it. 
    	List<O> newLeft = new ArrayList<>(left);
    	newLeft.addAll(right);
        return newLeft;
    });
}
 
Example 4
Source File: FilterUsingReduce.java    From https-github.com-RichardWarburton-java-8-Lambdas-exercises with MIT License 6 votes vote down vote up
public static <I> List<I> filter(Stream<I> stream, Predicate<I> predicate) {
    List<I> initial = new ArrayList<>();
    return stream.reduce(initial,
                         (List<I> acc, I x) -> {
                            if (predicate.test(x)) {
                            	// We are copying data from acc to new list instance. It is very inefficient,
                            	// but contract of Stream.reduce method requires that accumulator function does
                            	// not mutate its arguments.
                            	// Stream.collect method could be used to implement more efficient mutable reduction,
                            	// but this exercise asks to use reduce method explicitly.
                            	List<I> newAcc = new ArrayList<>(acc);
                                newAcc.add(x);
                                return newAcc;
                            } else {
                            	return acc;
                            }
                         },
                         FilterUsingReduce::combineLists);
}
 
Example 5
Source File: PermissionSubjectsMap.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the set of subjects each of which is related to <em>all</em> given permissions.
 *
 * @param permissions The set of permissions to check.
 * @return The set of subjects each of which is related to all given permissions.
 * @throws NullPointerException if {@code permissions} is {@code null}.
 */
Map<String, Integer> getSubjectIntersect(final Set<String> permissions) {
    validatePermissions(permissions);

    final Stream<Map<String, Integer>> subjectsOfPermissions = intersect(keySet(), permissions).map(this::get);

    final Optional<Map<String, Integer>> reduceResult = subjectsOfPermissions.reduce((map1, map2) ->
            intersect(map1.keySet(), map2.keySet())
                    .collect(Collectors.toMap(Function.identity(), key -> Math.max(map1.get(key), map2.get(key)))));

    return reduceResult.orElse(Collections.emptyMap());
}
 
Example 6
Source File: Fold.java    From beam with Apache License 2.0 5 votes vote down vote up
/**
 * Return a {@link ReduceFunctor} that performs a fold operation and emits result after fold of
 * all input data.
 *
 * @param <T> element type
 * @param identity the zero element
 * @param fold the associative fold function
 * @return the {@link CombinableReduceFunction}
 */
public static <T> ReduceFunctor<T, T> of(T identity, BinaryFunctor<T, T, T> fold) {
  return (Stream<T> s, Collector<T> ctx) -> {
    final SingleValueContext<T> wrap = new SingleValueContext<>(ctx.asContext());
    final T ret =
        s.reduce(
            identity,
            (a, b) -> {
              fold.apply(a, b, wrap);
              return wrap.getAndResetValue();
            });
    ctx.collect(ret);
  };
}
 
Example 7
Source File: BigDecimalUtil.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static <$ extends Object> BigDecimal sum(Stream<BigDecimal> stream) {
    return stream.reduce(BigDecimal.ZERO, reducer);
}
 
Example 8
Source File: Executor.java    From tutorials with MIT License 4 votes vote down vote up
public static int countAutors(Stream<Author> stream) {
	RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true),
			RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine);
	return wordCounter.getCounter();
}
 
Example 9
Source File: Combine.java    From cyclops with Apache License 2.0 4 votes vote down vote up
default <T> Higher<CRE,T> plus(Higher<CRE, T> identity, BinaryOperator<Higher<CRE, T>> accumulator, Stream<Higher<CRE, T>> tocombine){
    return  tocombine.reduce(identity, accumulator);
}
 
Example 10
Source File: Question1.java    From java-8-lambdas-exercises with MIT License 4 votes vote down vote up
public static int addUp(Stream<Integer> numbers) {
    return numbers.reduce(0, (acc, x) -> acc + x);
}
 
Example 11
Source File: SumsTest.java    From beam with Apache License 2.0 4 votes vote down vote up
private <T> T apply(Stream<T> stream, ReduceByKey.CombineFunctionWithIdentity<T> fn) {
  return stream.reduce(fn.identity(), fn::apply);
}
 
Example 12
Source File: AddNumbersUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
public void givenStreamOfIntegers_whenUsingReduceToSum_thenResultIsCorrect() {
    Stream<Integer> intNumbers = Stream.of(0, 1, 2);
    int result = intNumbers.reduce(0, Integer::sum);
    assertEquals(106, result);
}
 
Example 13
Source File: WalkFunction.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
static Optional<StackFrame> reduce(Stream<StackFrame> stream) {
    return stream.reduce((r,f) -> r.getClassName().compareTo(f.getClassName()) > 0 ? f : r);
}
 
Example 14
Source File: Question1.java    From https-github.com-RichardWarburton-java-8-Lambdas-exercises with MIT License 4 votes vote down vote up
public static int addUp(Stream<Integer> numbers) {
    return numbers.reduce(0, (acc, x) -> acc + x);
}
 
Example 15
Source File: Test73.java    From blog with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private static int countWords(Stream<Character> stream) {
	WordCounter wordCounter = stream.reduce(new WordCounter(0, true), WordCounter::accumulate,
			WordCounter::combine);
	return wordCounter.getCounter();
}
 
Example 16
Source File: AddNumbersUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
public void givenStreamOfBigDecimals_whenUsingReduceToSum_thenResultIsCorrect() {
    Stream<BigDecimal> bigDecimalNumber = Stream.of(BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN);
    BigDecimal result = bigDecimalNumber.reduce(BigDecimal.ZERO, BigDecimal::add);
    assertEquals(11, result);
}
 
Example 17
Source File: AnyM.java    From cyclops with Apache License 2.0 3 votes vote down vote up
public static  <W extends WitnessType<W>,T> AnyM<W,Stream<T>> sequence(Stream<? extends AnyM<W,T>> stream, W witness) {
    MonadAdapter<W> c = witness.adapter();
    AnyM<W,Stream<T>> identity = c.unit(ReactiveSeq.empty());

    BiFunction<AnyM<W,Stream<T>>,AnyM<W,T>,AnyM<W,Stream<T>>> combineToStream = (acc,next) -> c.ap2(c.unit(Lambda.l2((Stream<T> a)->(T b)->ReactiveSeq.concat(a,ReactiveSeq.of(b)))),acc,next);

    BinaryOperator<AnyM<W,Stream<T>>> combineStreams = (a,b)-> (AnyM<W,Stream<T>>)a.zip(b,(z1,z2)->(Stream<T>)ReactiveSeq.concat(z1,z2)); // a.applyHKT(b, (s1,s2)->s1);

    return stream.reduce(identity,combineToStream,combineStreams);
}
 
Example 18
Source File: Either.java    From cyclops with Apache License 2.0 3 votes vote down vote up
public static  <L,T> Either<L,Stream<T>> sequence(Stream<? extends Either<L,T>> stream) {

    Either<L, Stream<T>> identity = Either.right(ReactiveSeq.empty());

    BiFunction<Either<L,Stream<T>>,Either<L,T>,Either<L,Stream<T>>> combineToStream = (acc,next) ->acc.zip(next,(a,b)->ReactiveSeq.fromStream(a).append(b));

    BinaryOperator<Either<L,Stream<T>>> combineStreams = (a,b)-> a.zip(b,(z1,z2)->ReactiveSeq.fromStream(z1).appendStream(z2));

   return stream.reduce(identity,combineToStream,combineStreams);
  }
 
Example 19
Source File: Monad.java    From cyclops with Apache License 2.0 3 votes vote down vote up
default <T> Higher<CRE,Stream<T>> sequence(Stream<Higher<CRE, T>> stream) {
    Higher<CRE,Stream<T>> identity = unit(Stream.empty());

    BiFunction<Higher<CRE,Stream<T>>,Higher<CRE,T>,Higher<CRE,Stream<T>>> combineToStream = (acc,next) -> ap2(unit(a->b->Stream.concat(a,Stream.of(b))),acc,next);

    BinaryOperator<Higher<CRE,Stream<T>>> combineStreams = (a,b)->a.applyHKT(b, (s1, s2)->s1);

    return stream.reduce(identity,combineToStream,combineStreams);
}
 
Example 20
Source File: Seq.java    From protonpack with MIT License 2 votes vote down vote up
/**
 * Creates a sequence from a stream by consing each item onto an initially empty stream. Note that the resulting sequence will be in reverse order.
 * @param stream The stream of values to put in the sequence.
 * @param <T> The type of the items.
 * @return The created sequence.
 */
static <T> Seq<T> of(Stream<T> stream) {
    return stream.reduce(empty(), Seq::cons, Seq::append);
}