YJ의 새벽

JAVA ( 메서드참조 ) 본문

SelfStudy/JAVA

JAVA ( 메서드참조 )

YJDawn 2023. 2. 9. 15:12

람다식과, 함수형인터페이스 알고봐야합니다.

 

 

** 메서드참조  (클래스이름 :: 메서드이름)

                        

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

 

--static 메서드참조              (x)  -> 클래스명.method(x)     =   클래스명 ::  method

                                                                람다식          ---- >         메서드참조

--인스턴스메서드 참조      (obj,x) -> obj.method(x)   =     클래스명 :: method

                                                             람다식          ---- >       메서드참조

 

 

    EX )))) 

import java.util.function.Function;

public class Example6 {

	public static void main(String[] args) {
		
		//Supplier 입력X 출력O
//		Supplier<MyClass> s = () -> new MyClass();        // 람다식
//		Supplier<MyClass> s = MyClass :: new;          // 메서드참조
//		System.out.println(s.get());
		
//		Function<Integer, MyClass> f = (i) -> new MyClass(i); //람다식   
		Function<Integer, MyClass> f = MyClass :: new;        // 메서드참조
		System.out.println(f.apply(100).iv);
		
//		Function<Integer, int[]> f2 = (i) ->new int[i];      //람다식
		Function<Integer, int[]> f2 = int[] :: new;		     //메서드참조
		System.out.println(f2.apply(100).length);
		
	}
}
class MyClass{
	int iv;
	
	MyClass(int iv){
		this.iv = iv;
	}
}

 

 

 

 

 

'SelfStudy > JAVA' 카테고리의 다른 글

JAVA ( 스트림의 그룹화,분할 )  (0) 2023.02.12
JAVA ( 스트림 )  (0) 2023.02.10
JAVA ( 함수형인터페이스 )  (0) 2023.02.09
JAVA ( 람다식 )  (0) 2023.02.09
JAVA ( 쓰레드의 동기화 )  (0) 2023.02.08
Comments