下面列出了java.util.stream.Stream#reduce ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
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;
});
}
/**
* 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());
}
/**
* 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);
};
}
public static int countAutors(Stream<Author> stream) {
RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true),
RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine);
return wordCounter.getCounter();
}
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);
}
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);
}
static Optional<StackFrame> reduce(Stream<StackFrame> stream) {
return stream.reduce((r,f) -> r.getClassName().compareTo(f.getClassName()) > 0 ? f : r);
}
public void givenStreamOfIntegers_whenUsingReduceToSum_thenResultIsCorrect() {
Stream<Integer> intNumbers = Stream.of(0, 1, 2);
int result = intNumbers.reduce(0, Integer::sum);
assertEquals(106, result);
}
private <T> T apply(Stream<T> stream, ReduceByKey.CombineFunctionWithIdentity<T> fn) {
return stream.reduce(fn.identity(), fn::apply);
}
public static int addUp(Stream<Integer> numbers) {
return numbers.reduce(0, (acc, x) -> acc + x);
}
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);
}
public static <$ extends Object> BigDecimal sum(Stream<BigDecimal> stream) {
return stream.reduce(BigDecimal.ZERO, reducer);
}
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);
}
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);
}
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);
}
/**
* 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);
}