java8:来自另一个方法引用的方法引用

ewo*_*wok 15 java lambda java-8

我想使用基于另一个方法引用的方法引用.这很难解释,所以我给你举个例子:

Person.java

public class Person{
    Person sibling;
    int age;

    public Person(int age){
        this.age = age;
    }

    public void setSibling(Person p){
        this.sibling = p;
    }

    public Person getSibling(){
        return sibling;
    }

    public int getAge(){
        return age;
    }
}
Run Code Online (Sandbox Code Playgroud)

给定一个Persons 列表,我想使用方法引用来获取其兄弟年龄的列表.我知道这可以这样做:

roster.stream().map(p -> p.getSibling().getAge()).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有可能更像这样:

roster.stream().map(Person::getSibling::getAge).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

在这个例子中它并不是非常有用,我只是想知道什么是可能的.

Tun*_*aki 13

map在这种情况下,您需要使用两个操作:

roster.stream().map(Person::getSibling).map(Person::getAge).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

第一个映射Person到它的兄弟,第二个映射Person到它的年龄.