2016-03-24 32 views
13

我想使用基於另一個方法引用的方法引用。這是一種很難解釋的,所以我給你舉個例子:java8:從另一個方法引用的方法參考

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

鑑於Person個清單,我想用方法的引用來獲得列表他們的兄弟姐妹的年齡。我知道這是可以做到這樣的:

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

但我不知道是否有可能做到這一點更是這樣的:

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

它在這個例子並不十分有用的,我只是想知道什麼是可能的。

+6

[地圖鏈方法參考](http://stackoverflow.com/questions/26920866/chain-of-map-method-references) – rgettman

回答

13

你需要在這種情況下使用兩個map操作:

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

第一個Person映射到其兄弟,第二個映射Person到它的年齡。

2

您可以使用Functions.chain()Eclipse Collections到鏈方法參考:

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

由於年齡是一個int改變,您可以通過使用避免裝箱一個IntList

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

注:我是Eclipse Collections的貢獻者。

1

使用Function.andThen,並且可能將您的第一個方法引用包含在調用或投射中。

public static <V, R> Function<V,R> ofFunction(Function<V,R> function) { 
    return function; 
} 

roster.collect(ofFunction(Person::getSibling).andThen(Person::getAge));