본문 바로가기

JAVA

람다6 메소드 참조

생성자의 메서드 참조

 

메서드 참조 (method reference)

하나의 메서드만 호출하는 람다식은 메서드 참조로 간단히 표현할 수 있다.

람다식을 더 간단히 한다.

 

static 메서드 참고

(x) -> className.method(x) 

의 람다식을 메소드 참조로 변환

className::method(x)

 

인터페이스 메서드 참조

(obj x) -> obj.method(x)

위 메서드를 메서드 참조로 변환

className::method

 

메서드 참조 = 클래스이름 :: 메서드 이름

 

static 메서드 참조

Integer method (String s) {  //그저 Integer.parseInt(String s) 만 호출하는 일반 메서드

 return Integer.parseInt(s);

}

 

//Integer.parseInt 를 호출하는 람다식

Function<String , Integer> f = (String s) -> Integer.parseInt(s); // 람다식 

 

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

 

Function<매개변수(입력) , 반환값(출력) > f = Integer(클래스명)::parseInt(메서드명); 

 

메서드 참조는 람다식을 간단히 쓰기위해 사용

메소드 참조돠 람다식으로 서로 바꿀줄 알아야 한다.

1.입력이 뭔지 볼것

2.출력이 뭔지 볼것

3.동작메서드를 볼것

 

입력이 있고 출력도 있는 function

Function<T , R> f = (String s) -> Integer.paeseInt(s);

Function<String , Integer> f = (String s) -> Integer.parseInt(s);

 

사용

f.apply("100") = f 에 매개변수 "100"을 넣어 적용

 

메서드 참조

클래스이름 :: 메서드 이름

Function<String , Integer> f = Integer :: parseInt;

 

생성자의 메서드 참조 

Supplier<myClass> s = () -> new MyClass();

//supplier는 입력이 없고 출력만 있다.

 

메서드 참조

Supplier<myClass> s = myClass::new;

 

생성자에 매개변수가 있는 경우

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

 

메서드 참조

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

 

Bifunction 매개변수가 2개인 경우 리턴이 있을 경우

 

배열과 메서드 참조

Function<Integer , int[]> f = x-> new Int[x] 

메서드 참조

Function<Integer , int[]> f2 = int[]::new

 

Supplier<MyClass> s = () -> new MyClass();

MyClass mc = s.get();

 

메서드 참조

Supplier<MyClass> s = MyClass::new

 

생성자가 있을 경우 매개변수가 필요, Function을 사용

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

Function<Integer , MyClass> f = MyClass::new

f.apply(100);

 

배열생성

Function<Integer , int[]> f2 = (i) -> new Int[i];

Function<Integer , int[]> f2 = Int[]::new;

'JAVA' 카테고리의 다른 글

스트림2 스트림의 중간연산  (0) 2023.03.15
스트림1 스트림의 특징  (0) 2023.03.15
람다5 함수 두개를 연결 andThan  (0) 2023.03.15
람다4 Predicate 람다 조건식  (0) 2023.03.15
람다3 함수형 인터페이스  (0) 2023.03.15