티스토리 뷰
람다식
인터페이스를 구현하는 익명 클래스의 객체 생성 부분을 수식화 한 것
구현할 것이 1개의 추상 메소드일 때 간단히 표현할 수 있음
1 2 3 4 5 | Runnable runnable = new Runnable() { public void run() { ... } } | cs |
람다식 구문
- 메소드 매개변수의 괄호, 화살표, 메소드 몸체로 표현
- 인터페이스 객체변수 = (매개변수목록) -> { 실행문목록 }
1 | Runnable runnable = () -> {...} | cs |
람다식 기본 문법
익명 구현 클래스의 객체 생성 부분만 람다식으로 표현함
- 익명 서브 클래스의 객체 생성은 람다식이 될 수 없음
l 이때 인터페이스에는 추상 메소드가 1개만 있어야 함
- 2개 이상의 추상 메소드를 포함하는 인터페이스는 사용 불가
람다식의결과 타입을 타깃 타입이라고함
1개의 추상 메소드를 포함하는 인터페이스를 함수적 인터페이스라함
- 메소드가1개뿐이므로메소드 이름을 생략할 수 있음
인터페이스 객체변수 =(매개변수목록)->{실행문목록}
매개변수 목록에서 자료형은 인터페이스 정의에서 알 수 있으므로 변수 이름만 사용 가능
매개변수가 1개면 괄호가 생략 가능하며 변수 이름 하나만 남음
매개변수를 가지지 않으면 괄호만 남음
실행문이 1개이면 중괄호 생략 가능
실행문이return문 뿐이라면 retrun과 중괄호를 동시 생략해야함
람다식 사용 예
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | interface MyInterface1 { public void method(int a, int b); } interface MyInterface2 { public void method(int a); } public class LambdaTest1 { public static void main(String args[]) { MyInterface1 f1, f2, f3; MyInterface2 f4, f5; f1 = (int a, int b)->{ System.out.println(a + b); }; f1.method(3, 4); f2 = (a, b)->{ System.out.println(a + b); }; f2.method(5, 6); f3 = (a,b)->System.out.println(a + b); f3.method(7, 8); f4 = (int a)->{ System.out.println(a); }; f4.method(9); f5 = a->System.out.println(a); f5.method(10); } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | interface MyInterface3 { public int method(int a, int b); } public class LambdaTest2{ public static void main(String args[]){ MyInterface3 f1,f2; //f1=(a,b)->returna + b; // 컴파일 에러 f1 = (a, b)->{ returna + b; }; System.out.println(f1.method(3, 4)); f2 = (a, b)->a + b; System.out.println(f2.method(5, 6)); } } | cs |
1 2 3 4 5 6 | public class RunnableTest4 { public static void main(String args[]) { Thread thd = new Thread(()->System.out.println("mythread")); thd.start(); } } | cs |
1 2 3 4 5 6 7 8 | import java.util.function.*; public class ConsumerTest{ public static void main(String args[]){ Consumer<String>c on = t->System.out.println("Hello" + t); con.accept("Java"); } } | cs |