-
메소드 레퍼런스프로그래밍/Java 2022. 6. 8. 22:44
람다가 하는 일이 기존 메소드 또는 생성자를 호출하는 거라면, 메소드 레퍼런스를 사용해서 간결하게 표현할 수 있다.
즉, 람다식을 더 간결하게 표현하는 방법이 메소드 레퍼런스 이다.
메소드를 참조하는 방법
- 메소드 또는 생성자의 매개변수로 람다의 입력값을 받는다.
- 리턴값 또는 생성한 객체는 람다의 리턴값이다.
아래 예제코드를 살펴보자.
import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.function.Supplier; import java.util.function.UnaryOperator; public class App { public static void main(String[] args) { // 1. 입력값을 받는 생성자 호출 및 인스턴스 생성 Function<String, Greeting> hkGreeting = Greeting::new; Greeting hyokeun = hkGreeting.apply("hyokeun"); System.out.println(hyokeun.getName()); // 2. 기본 생성자 호출 및 인스턴스 생성 Supplier<Greeting> newGreeting = Greeting::new; Greeting greeting = newGreeting.get(); // 3. instance method 참조 // Greeting greeting = new Greeting(); UnaryOperator<String> instanceMethod = greeting::hello; System.out.println(instanceMethod.apply("hyokeun")); // 4. static method 참조 UnaryOperator<String> staticMethod = Greeting::hi; System.out.println(staticMethod.apply("hyokeun")); // 5. 임의 객체의 인스턴스 메소드 참조 List<String> names = Arrays.asList("z", "b", "c", "a"); // String 에 static 한 메소드가 있는게 아니다. 임의 객체의 인스턴스 메소드를 참조하고 있는것이다. names.sort(String::compareToIgnoreCase); System.out.println(names.toString()); // [a, b, c, z] } }
'프로그래밍 > Java' 카테고리의 다른 글
CompletableFuture (3) - Callable 과 Future (0) 2022.06.14 인터페이스 default 메소드와 static 메소드 (0) 2022.06.09 자바에서 제공하는 함수형 인터페이스 (0) 2022.06.07 함수형 인터페이스와 람다 표현식 소개 (0) 2022.06.07 Metaspace (0) 2022.05.06