Calling Stream.map with a method reference returning an int
Eirik Bjørsnøs
eirbjo at gmail.com
Tue Jan 29 05:10:56 PST 2013
I'm trying to understand why I can't use method references the way my
intuition wants it to work :-)
Given the following class:
public class Person {
private int age;
private String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() { return age;}
public String getName() {return name;}
}
I can print a sorted list of names using this (elegant!) piece of Java 8
code: (given List<Person> list):
list.stream().map(Person::getName).sorted(String::compareTo).forEach(System.out::println);
Now, say I want to calculate the sum of ages. I can map the age using a
lambda expressions and then call IntStream.sum(), like this:
long sum = list.stream().map(p->p.getAge()).sum();
However, when I try to replace the lambda expression "p -> p.getAge" with
the method reference "Person::getAge", I get a compiler error:
long sum = list.stream().map(Person::getAge).sum();
java: cannot find symbol
symbol: method sum()
location: interface java.util.stream.Stream<java.lang.Long>
In this case, calling Stream.map with Person::getAge is resolved to
Stream.map(Function<? super T, ? extends R> mapper) which returns a
Stream<Long>. While what I wanted was Stream.map(IntFunction<? super T>
mapper) which returns an IntStream.
So why is Person::getAge not considered an IntFunction? Could it? Should
it? Am I missing something?
I'm using build 1.8.0-ea-b74.
Eirik.
More information about the lambda-dev
mailing list