Java IntStream reduce to sum

Introduction

The reduce() method takes an identity and an accumulator.

Then reduce the stream to a single value of the same type.

import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> numbers  = Arrays.asList(1, 2, 3, 4, 5);
    int sum = numbers.stream()
    .reduce(0, Integer::sum); /*from ww w . ja  va  2  s  .  co m*/
    System.out.println(sum);
  }
}



PreviousNext

Related