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

2022-09-03 01:56:15

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

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

给定一个列表,我想使用方法引用来获取其兄弟姐妹的年龄列表。我知道这可以像这样完成:Person

roster.stream().map(p -> p.getSibling().getAge()).collect(Collectors.toList());

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

roster.stream().map(Person::getSibling::getAge).collect(Collectors.toList());

在这个例子中,这并不是很有用,我只是想知道什么是可能的。


答案 1

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

roster.stream().map(Person::getSibling).map(Person::getAge).collect(Collectors.toList());

第一个将 映射到其兄弟,第二个将 映射到其年龄。PersonPerson


答案 2

您可以使用 Eclipse Collections 来链接方法引用:Functions.chain()

MutableList<Person> roster = Lists.mutable.empty();
MutableList<Integer> ages = 
    roster.collect(Functions.chain(Person::getSibling, Person::getAge));

如果您无法更改花名册List

List<Person> roster = Lists.mutable.empty();
List<Integer> ages =
    ListAdapter.adapt(roster).collect(Functions.chain(Person::getSibling, Person::getAge));

由于年龄是一个 ,因此您可以使用 IntList 避免装箱:int

MutableList<Person> roster = Lists.mutable.empty();
IntList ages = roster.collectInt(Functions.chainInt(Person::getSibling, Person::getAge));

注意:我是 Eclipse Collections 的贡献者。


推荐