Java Stream How to - Reduce to sum numbers








Question

We would like to know how to reduce to sum numbers.

Answer

import java.util.Optional;
import java.util.stream.Stream;
// w  w w  . jav  a  2 s .c  o  m
public class Main {

  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);
  }
}

The code above generates the following result.