본문 바로가기
Study/Java

[Java] Lambda 람다식

by JYHAN 2020. 7. 3.

기존의 객체 지향이 아닌 함수 지향 프로그래밍 방법

람다식이란?

익명 함수(Anonymous Function)를 이용해서 익명 객체를 생성하기 위한 식

 

[ 기존 방법 ]

InterfaceType 변수 --- 할당(대입) ---> Interface 구현

 

[ 람다식 방법 ]

InterfaceType 변수 --- 할당(대입) ---> Lambda Expressions

 

람다식 구현

1. 매개변수와 실행문만으로 작성한다(접근자, 반환형, return 키워드 생략)

public interface LambdaInterface {
	public void method(String s1, String s2, String s3);
}

public static void main(String[] args) {
	LambdaInterface li = (String s1, String s2, String s3) -> {System.out.println(s1 + " " + s2 + " " + s3);};
	li.method("Hello", "java", "World");
}

---- result ----
Hello java World

 

2. 매개변수가 1개이거나 타입이 같을 때, 타입을 생략할 수 있다

public interface LambdaInterface {
	public void method(String s1);
}

public static void main(String[] args) {
	LambdaInterface li = (s1) -> {System.out.println(s1);};
	li.method("Hello");
}

---- result ----
Hello

 

3.실행문이 1개일 때, '{ }'를 생략할 수 있다

public interface LambdaInterface {
	public void method(String s1);
}

public static void main(String[] args) {
	LambdaInterface li = (s1) -> System.out.println(s1);
	li.method("Hello");
}

---- result ----
Hello

 

4. 매개변수와 실행문이 1개일 때, '( )'와 '{ }'를 생략할 수 있다

public interface LambdaInterface {
	public void method(String s1);
}

public static void main(String[] args) {
	LambdaInterface li = s1 -> System.out.println(s1);
	li.method("Hello");
}

---- result ----
Hello

 

5. 매개변수가 없을 때, '( )'만 작성한다

public interface LambdaInterface {
	public void method();
}

public static void main(String[] args) {
	LambdaInterface li = () -> System.out.println("no parameter");
	li.method();
}

---- result ----
no parameter

 

6. 반환 값이 있는 경우

public interface LambdaInterface {
	public int method(int x, int y);
}

public static void main(String[] args) {
	// 데이터 타입이 같기 때문에 int 생략!!
	LambdaInterface li = (x, y) -> {
		int result = x + y;
		return result;
	};
	System.out.printf("li.method(10,20) : %d\n", li.method(10,20));
}

---- result ----
li.method(10,20) : 30

댓글