14-13~14 메서드 참조, 생성자의 메서드 참조

oyeon·2021년 3월 22일
0

Java 개념

목록 보기
64/70

메서드 참조(method reference)

  • 하나의 메서드만 호출하는 람다식은 '메서드 참조'로 더 간단히 할 수 있다.
  • static 메서드 참조, 인스턴스 메서드 참조만 알면된다.

static 메서드 참조

// Function<String, Integer> 부분에서 입력이 String이고 출력이 Integer라는
// 사실을 알려줬으므로 뒤에서는 생략할 수 있다는 느낌으로 이해하면 된다.
Function<String, Integer> f = (String s) -> Integer.parseInt(s);

위 문장을 아래와 같이 쓸 수 있다.

Function<String, Integer> f = Integer::parseInt;	// 메서드 참조

생성자의 메서드 참조

생성자와 메서드 참조

Supplier<MyClass> s = () -> new MyClass();
Function<Integer, MyClass> s = (i) -> new MyClass(i);

위 코드를 아래와 같이 쓸 수 있다.

Supplier<MyClass> s = MyClass::new;
Function<Integer, MyClass> s = MyClass::new;

배열과 메서드 참조(많이씀)

Function<Integer, int[]> f = x -> new int[x];	// 람다식
Function<Integer, int[]> f2 = int[]::new;	// 메서드 참조
profile
Enjoy to study

0개의 댓글