Java Code Examples for java.util.stream.Stream#reduce()
The following examples show how to use
java.util.stream.Stream#reduce() .
These examples are extracted from open source projects.
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 Project: Alink File: Params.java License: Apache License 2.0 | 6 votes |
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 Project: https-github.com-RichardWarburton-java-8-Lambdas-exercises File: MapUsingReduce.java License: MIT License | 6 votes |
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 Project: https-github.com-RichardWarburton-java-8-Lambdas-exercises File: FilterUsingReduce.java License: MIT License | 6 votes |
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 4
Source Project: java-8-lambdas-exercises File: MapUsingReduce.java License: MIT License | 6 votes |
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 5
Source Project: ditto File: PermissionSubjectsMap.java License: Eclipse Public License 2.0 | 5 votes |
/** * 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 Project: beam File: Fold.java License: Apache License 2.0 | 5 votes |
/** * 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 Project: tutorials File: Executor.java License: MIT License | 4 votes |
public static int countAutors(Stream<Author> stream) { RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true), RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine); return wordCounter.getCounter(); }
Example 8
Source Project: tutorials File: AddNumbersUnitTest.java License: MIT License | 4 votes |
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 9
Source Project: blog File: Test73.java License: BSD 2-Clause "Simplified" License | 4 votes |
private static int countWords(Stream<Character> stream) { WordCounter wordCounter = stream.reduce(new WordCounter(0, true), WordCounter::accumulate, WordCounter::combine); return wordCounter.getCounter(); }
Example 10
Source Project: https-github.com-RichardWarburton-java-8-Lambdas-exercises File: Question1.java License: MIT License | 4 votes |
public static int addUp(Stream<Integer> numbers) { return numbers.reduce(0, (acc, x) -> acc + x); }
Example 11
Source Project: openjdk-jdk9 File: WalkFunction.java License: GNU General Public License v2.0 | 4 votes |
static Optional<StackFrame> reduce(Stream<StackFrame> stream) { return stream.reduce((r,f) -> r.getClassName().compareTo(f.getClassName()) > 0 ? f : r); }
Example 12
Source Project: tutorials File: AddNumbersUnitTest.java License: MIT License | 4 votes |
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 Project: beam File: SumsTest.java License: Apache License 2.0 | 4 votes |
private <T> T apply(Stream<T> stream, ReduceByKey.CombineFunctionWithIdentity<T> fn) { return stream.reduce(fn.identity(), fn::apply); }
Example 14
Source Project: java-8-lambdas-exercises File: Question1.java License: MIT License | 4 votes |
public static int addUp(Stream<Integer> numbers) { return numbers.reduce(0, (acc, x) -> acc + x); }
Example 15
Source Project: cyclops File: Combine.java License: Apache License 2.0 | 4 votes |
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 16
Source Project: fenixedu-academic File: BigDecimalUtil.java License: GNU Lesser General Public License v3.0 | 4 votes |
public static <$ extends Object> BigDecimal sum(Stream<BigDecimal> stream) { return stream.reduce(BigDecimal.ZERO, reducer); }
Example 17
Source Project: cyclops File: AnyM.java License: Apache License 2.0 | 3 votes |
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 Project: cyclops File: Either.java License: Apache License 2.0 | 3 votes |
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 Project: cyclops File: Monad.java License: Apache License 2.0 | 3 votes |
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 Project: protonpack File: Seq.java License: MIT License | 2 votes |
/** * 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); }