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

T reduce(T identity, BinaryOperator<T> accumulator);

Source Link

Document

Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.

Usage

From source file:Main.java

public static void main(String[] args) {
    List<Person> persons = Arrays.asList(new Person("FooBar", 12), new Person("BarFoo", 16));
    Stream<Integer> stream = persons.stream().map(x -> x.getAge());
    int sum = stream.reduce(0, (l, r) -> l + r);
    System.out.println(sum);/*from  w  w  w.ja v  a  2s .com*/
}

From source file:com.ejisto.event.listener.SessionRecorderManager.java

private void tryToSave(final String contextPath) {
    final Set<CollectedData> data = RECORDED_DATA.replace(contextPath, new HashSet<>());
    if (CollectionUtils.isEmpty(data)) {
        log.debug("Nothing to save, exiting");
        return;/*from  ww  w .j  ava2  s. com*/
    }
    String name;
    do {
        name = showInputDialog(null, getMessage("session.record.save.as"),
                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));

    } while (StringUtils.isEmpty(name) && !GuiUtils.showWarning(null, getMessage("warning.message")));

    if (StringUtils.isNotEmpty(name)) {
        final CollectedData collectedData;
        if (data.size() > 1) {
            final Stream<CollectedData> stream = data.stream();
            CollectedData aggregated = CollectedData.empty(stream.findFirst().get().getRequestURI(),
                    contextPath);
            collectedData = stream.reduce(aggregated, CollectedData::join);
        } else {
            collectedData = data.iterator().next();
        }
        collectedDataRepository.saveRecordedSession(name, collectedData);

        eventManager.publishEvent(
                new SessionRecorded(this, name, getMessage("session.recorded.status.message", name)));
    }
}