Java Stream How to - Map a Stream to type Integer and then sum() with Lambdas








Question

We would like to know how to map a Stream to type Integer and then sum() with Lambdas.

Answer

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
//  w ww.ja  v  a  2  s  .  co m
public class Main {
  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);
  }

}

class Person {
  private final String name;
  private final Integer age;

  public Person(String name, Integer age) {
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }

  public Integer getAge() {
    return age;
  }
}

The code above generates the following result.