2016-03-24 23 views
13

別のメソッド参照に基づくメソッド参照を使用したいと思います。それは説明するのは難しいのようなものだ、私はあなたに例をあげる:Personのリストを考えると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; 
    } 
} 

、私はのリストを取得する方法の参照を使用したいです彼らの兄弟の年齢。

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

あなたは、その場合には2つのmap操作を使用する必要があります。

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

最初のものは、その兄弟にPersonをマップする2つ目は、その年齢にPersonをマップします。

2

あなたは連鎖方式参照にEclipse CollectionsからFunctions.chain()を使用することができます。

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

年齢はintあるので、あなたはList

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

から名簿を変更できない場合は、あなたが使用してボクシングを避けることができます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));