람다식

Dana's Log·2022년 5월 15일
0

//매개변수로 정수 값 나이를 받아 출력하는 람다식
(int age) -> { System.out.println("나이는 " + age); }
(age) -> { System.out.println("나이는 " + age); } // int 타입 생략
age -> System.out.println("나이는 " + age); // ()와 {} 생략

//x, y 두 값을 받아 합을 출력하는 람다식
(int x, int y) -> { System.out.println(x + y); }
(x, y) -> System.out.println(x + y);

//매개변수 x, y의 값을 합하여 리턴하는 람다식
(x, y) -> { return x + y; } // 합을 리턴하는 람다식
//(x, y) -> return x + y; // 오류. {} 생략 안 됨
(x, y) -> x + y; // return 생략 가능. x+y의 합을 리턴하는 람다식


interface MyFunction { // 함수형 인터페이스
	int calc(int x, int y); // 람다식으로 구현할 추상 메소드
}

public class LambdaEx1 {
	public static void main(String[] args) {
       MyFunction add = (x, y) -> { return x + y; }; // 람다식
       MyFunction minus = (x, y) -> x - y; // 람다식. {}와 return 생략
       System.out.println(add.calc(1, 2)); // 합 구하기 // 3
       System.out.println(minus.calc(1, 2)); // 차 구하기 // -1
	}
}

매개변수 없는 람다식

interface MyFunction { // 함수형 인터페이스
	void print(); // 람다식으로 구현할 추상 메소드
}

public class LambdaEx3 {
	public static void main(String[] args) {
		 MyFunction f = () -> { // 람다식 작성
		 System.out.println("Hello");
 		};

		 f.print(); // 람다식 호출

 		f = () -> System.out.println("안녕"); // 람다식 작성

		 f.print(); // 람다식 호출
}
profile
다나로그

0개의 댓글