java.util.stream.Stream#reduce ( )源码实例Demo

下面列出了java.util.stream.Stream#reduce ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Alink   文件: Params.java
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);
		}));
}
 
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;
    });
}
 
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);
}
 
源代码4 项目: java-8-lambdas-exercises   文件: MapUsingReduce.java
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;
    });
}
 
源代码5 项目: ditto   文件: PermissionSubjectsMap.java
/**
 * 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());
}
 
源代码6 项目: beam   文件: Fold.java
/**
 * 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);
  };
}
 
源代码7 项目: tutorials   文件: Executor.java
public static int countAutors(Stream<Author> stream) {
	RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true),
			RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine);
	return wordCounter.getCounter();
}
 
源代码8 项目: tutorials   文件: AddNumbersUnitTest.java
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);
}
 
源代码9 项目: blog   文件: Test73.java
private static int countWords(Stream<Character> stream) {
	WordCounter wordCounter = stream.reduce(new WordCounter(0, true), WordCounter::accumulate,
			WordCounter::combine);
	return wordCounter.getCounter();
}
 
public static int addUp(Stream<Integer> numbers) {
    return numbers.reduce(0, (acc, x) -> acc + x);
}
 
源代码11 项目: openjdk-jdk9   文件: WalkFunction.java
static Optional<StackFrame> reduce(Stream<StackFrame> stream) {
    return stream.reduce((r,f) -> r.getClassName().compareTo(f.getClassName()) > 0 ? f : r);
}
 
源代码12 项目: tutorials   文件: AddNumbersUnitTest.java
public void givenStreamOfIntegers_whenUsingReduceToSum_thenResultIsCorrect() {
    Stream<Integer> intNumbers = Stream.of(0, 1, 2);
    int result = intNumbers.reduce(0, Integer::sum);
    assertEquals(106, result);
}
 
源代码13 项目: beam   文件: SumsTest.java
private <T> T apply(Stream<T> stream, ReduceByKey.CombineFunctionWithIdentity<T> fn) {
  return stream.reduce(fn.identity(), fn::apply);
}
 
源代码14 项目: java-8-lambdas-exercises   文件: Question1.java
public static int addUp(Stream<Integer> numbers) {
    return numbers.reduce(0, (acc, x) -> acc + x);
}
 
源代码15 项目: cyclops   文件: Combine.java
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);
}
 
源代码16 项目: fenixedu-academic   文件: BigDecimalUtil.java
public static <$ extends Object> BigDecimal sum(Stream<BigDecimal> stream) {
    return stream.reduce(BigDecimal.ZERO, reducer);
}
 
源代码17 项目: cyclops   文件: AnyM.java
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);
}
 
源代码18 项目: cyclops   文件: Either.java
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);
  }
 
源代码19 项目: cyclops   文件: Monad.java
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);
}
 
源代码20 项目: protonpack   文件: Seq.java
/**
 * 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);
}