Example usage for java.util.stream Stream reduce

List of usage examples for java.util.stream Stream reduce

Introduction

In this page you can find the example usage for java.util.stream Stream reduce.

Prototype

Optional<T> reduce(BinaryOperator<T> accumulator);

Source Link

Document

Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.

Usage

From source file:Main.java

public static void main(String[] args) {

    // reduce numbers to their sum
    Stream<Integer> numbers = Stream.of(3, 5, 7, 9, 11);
    Optional<Integer> sum = numbers.reduce((x, y) -> x + y);
    sum.ifPresent(System.out::println);

    // reduce numbers to their sum with seed
    numbers = Stream.of(3, 5, 7, 9, 11);
    Integer sumWithSeed = numbers.reduce(0, (x, y) -> x + y);
    System.out.println(sumWithSeed);

    // reduce numbers to their sum with parallel stream
    Stream<String> words = Stream.of("All", "men", "are", "created", "equal");
    Integer lengthOfAllWords = words.reduce(0, (total, word) -> total + word.length(),
            (total1, total2) -> total1 + total2);
    System.out.println(lengthOfAllWords);
}

From source file:org.lightjason.agentspeak.beliefbase.view.CViewMap.java

/**
 * returns the leaf of a view path/*from   ww  w. j  a v a  2  s .c  om*/
 *
 * @param p_stream stream of views
 * @return last / leaf view
 */
@Nonnull
private IView leafview(@Nonnull final Stream<IView> p_stream) {
    return p_stream.reduce((i, j) -> j).orElse(this);
}

From source file:org.trellisldp.http.impl.MementoResource.java

private static Stream<Link> getTimeMap(final String identifier, final Stream<VersionRange> mementos) {
    return mementos.reduce((acc, x) -> new VersionRange(acc.getFrom(), x.getUntil())).map(x -> Link
            .fromUri(identifier + TIMEMAP_PARAM).rel(TIMEMAP).type(APPLICATION_LINK_FORMAT)
            .param(FROM, ofInstant(x.getFrom().minusNanos(1L).plusSeconds(1L), UTC).format(RFC_1123_DATE_TIME))
            .param(UNTIL, ofInstant(x.getUntil(), UTC).format(RFC_1123_DATE_TIME)).build())
            // TODO use Optional::stream with JDK9
            .map(Stream::of).orElseGet(Stream::empty);
}