본문

170427(목) - Method References

Method References


Lambda expressions 로 anonymous methods를 호출 가능하다.

하지만 때때로 람다는 기존 메소드를 호출하기만 함

→ 기존 메소드를 이름으로 참조하는것이 더 명확함


public class Person {

    public enum Sex {
        MALE, FEMALE
    }

    String name;
    LocalDate birthday;
    Sex gender;
    String emailAddress;

    public int getAge() {
        // ...
    }
    
    public Calendar getBirthday() {
        return birthday;
    }    

    public static int compareByAge(Person a, Person b) {
        return a.birthday.compareTo(b.birthday);
    }}


Person[] rosterAsArray = roster.toArray(new Person[roster.size()]);

class PersonAgeComparator implements Comparator<Person> {
    public int compare(Person a, Person b) {
        return a.getBirthday().compareTo(b.getBirthday());
    }
}
        
Arrays.sort(rosterAsArray, new PersonAgeComparator());



ㆍ람다 사용


Arrays.sort(rosterAsArray,
    (Person a, Person b) -> {
        return a.getBirthday().compareTo(b.getBirthday());
    }
);



ㆍ그러나 Person.compareByAge 로 이미 존재한다.


Arrays.sort(rosterAsArray,
    (a, b) -> Person.compareByAge(a, b)
);



ㆍ람다식이 기존 메소드를 호출하기 때문에 람다식 대신에 method reference 가 가능하다.


Arrays.sort(rosterAsArray, Person::compareByAge);



Person::compareByAge 는 의미론적으로 (a, b) -> person.compareByAge(a, b) 와 같다.



- Kinds of method references


KindExample
Reference to a static methodContainingClass::staticMethodName
Reference to an instance method of a particular objectcontainingObject::instanceMethodName
Reference to an instance method of an arbitrary object of a particular typeContainingType::methodName
Reference to a constructorClassName::new


ㆍreference to a Static Method

ㆍreference to an Instance Method of a Particular Object

class ComparisonProvider {
    public int compareByName(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }
        
    public int compareByAge(Person a, Person b) {
        return a.getBirthday().compareTo(b.getBirthday());
    }
}
ComparisonProvider myComparisonProvider = new ComparisonProvider();
Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);


ㆍreference to an Instance Method of an Arbitrary Object of a Particular Type

String[] stringArray = { "Barbara", "James", "Mary", "John",
    "Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase);


ㆍreference to a Constructor

public static <T, SOURCE extends Collection<T>, DEST extends Collection<T>>
    DEST transferElements(
        SOURCE sourceCollection,
        Supplier<DEST> collectionFactory) {
        
        DEST result = collectionFactory.get();
        for (T t : sourceCollection) {
            result.add(t);
        }
        return result;
}


Set<Person> rosterSetLambda =
    transferElements(roster, () -> { return new HashSet<>(); });


Set<Person> rosterSet = transferElements(roster, HashSet::new);


Set<Person> rosterSet = transferElements(roster, HashSet<Person>::new);


ㆍ여기서 <Person>은 추론 가능하다.

공유

댓글