Search code examples
javacollectionslambdajava-8

Java 8 Lambdas: Mapping a Stream to type Integer and then calling sum() won't compile


I was playing around with Java8 lambda expressions. As an example I then tried to sum up the ages persons contained in a list:

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

public class Person {
    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(new Person("FooBar", 12), new Person("BarFoo", 16));
        Integer sumOfAges = persons.stream().map(Person::getAge).sum();
        System.out.println("summedUpAges: " + sumOfAges);
    }

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

When I try to compile this snippet with the following java compiler:

openjdk version "1.8.0-ea"
OpenJDK Runtime Environment (build 1.8.0-ea-lambda-night
OpenJDK 64-Bit Server VM (build 25.0-b21, mixed mode)

I get the following compile error:

java: cannot find symbol
  symbol:   method sum()
  location: interface java.util.stream.Stream<java.lang.Integer>

But if I change the return value of the getAge() method from Integer to int, I get the expected result. But sometimes it is not possible or desired to change signatures on the fly. Is there any way to make this working when getAge() returns a Integer type?

Thanks in advance


Solution

  • I think they are changing the method

    IntStream map(ToIntFunction<? super T> mapper)
    

    to

    IntStream mapToInt(ToIntFunction<? super T> mapper)
    

    then your

    persons.stream().mapToInt(Person::getAge).sum()
    

    will always work, whether getAge() returns int or Integer.

    See this thread: http://mail.openjdk.java.net/pipermail/lambda-libs-spec-experts/2013-March/001480.html

    BTW you can post your questions to lambda-dev mailing list, they'd like to hear real world experiences.