메서드 참조(Method Reference)는 자바 8에서 도입된 기능으로, 람다 표현식이 단순히 메서드 호출만 수행할 때, 이를 간결하게 표현할 수 있도록 도와주는 문법입니다. 이는 람다의 축약형으로 볼 수 있으며, 코드의 간결성, 가독성, 재사용성을 높여줍니다.
BinaryOperator<Integer> add1 = (x, y) -> x + y;
BinaryOperator<Integer> add2 = (x, y) -> x + y;
BinaryOperator<Integer> add = (x, y) -> add(x, y);
static int add(int x, int y) { return x + y; }
(x, y) -> add(x, y) 형태 반복BinaryOperator<Integer> add = ClassName::add;
람다 표현식: (x) -> 클래스.메서드(x)
메서드 참조: 클래스명::메서드명
ClassName::staticMethodMath::max, Integer::parseIntobject::instanceMethodperson::introduceClassName::newPerson::newClassName::instanceMethodPerson::introduce, String::toUpperCase주의: 객체명이 아닌 클래스명을 사용한다는 점에서 2번과 구분됨. 실행 시점에 인스턴스를 매개변수로 받아 해당 메서드를 호출함.
Function<Person, String> f1 = (p) -> p.introduce();
Function<Person, String> f2 = Person::introduce;
List<String> result = list.stream()
.map(Person::introduce)
.map(String::toUpperCase)
.toList();
map(person -> person.introduce()) → Person::introducemap(s -> s.toUpperCase()) → String::toUpperCase()를 붙이지 않음