stream()_메소드 참조(작성중)

·2022년 11월 9일
0

메소드를 참조하여 매개변수의 정보 및 리턴타입을 알아낸 뒤 람다식에서 불필요한 매개변수를 제거함


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);

  • 인스턴스메소드는 객체이름으로 메소드 참조. 람다식을 아래와 같이 줄일 수 있다.
  • static 메소드는 객체가 아니라 클래스 이름으로 메소드를 참조함
        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);	
    }
    }
profile
웹개발입문자

0개의 댓글