메소드를 참조하여 매개변수의 정보 및 리턴타입을 알아낸 뒤 람다식에서 불필요한 매개변수를 제거함
class MyMath{
static int pow(int a) {return a*a;}
int abs(int a) {return a>0?a:-a;}
}
public class Test06_메소드참조 {
public static void main(String[] args) {
MyMath m = new MyMath();
Function<Integer, Integer> f = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer t) {
return m.abs(t);
}
};
int n = f.apply(-10);
System.out.println("n: "+n);
//람다식
Function<Integer, Integer> f1 =t->m.abs(t);
int n1 = f1.apply(-200);
System.out.println("n: "+n1);
Function<Integer, Integer> f2 =m::abs;
int n2 = f2.apply(-20);
System.out.println("n: "+n2);
Function<Integer, Integer> f3=(t)->MyMath.pow(t);
int n3 = f3.apply(-20);
System.out.println("n: "+n3);
Function<Integer, Integer> f4= MyMath::pow;
int n4 = f4.apply(-20);
System.out.println("n: "+n3);
Function<String, Integer> f5 = new Function<String, Integer>() {
@Override
public Integer apply(String t) {
return Integer.parseInt(t);
}
};
int n5 = f5.apply("1234");
System.out.println(n5);
Function<String, Integer> f6 =(t)->Integer.parseInt(t);
Function<String, Integer> f7 =Integer::parseInt;
int n6 = f6.apply("12345");
System.out.println(n6);
int n7 = f7.apply("1234567890");
System.out.println(n7);
ArrayList<String> as = new ArrayList<String>();
as.add("그레이몬");
as.add("가트몬");
as.add("가루몬");
as.add("엔젤몬");
//forEach문 메소드 참조 사용
as.forEach(t->System.out.println(t));
//여기에서 타입은 System.out이고 메소드는 println임
//파라미터타입 메소드
as.forEach(System.out::println);
}
}