티스토리 뷰

JAVA

Lambda Expression in Java

seoca 2019. 2. 22. 13:51



Lambda Expression 


It must be the *Functional Interface to use Lambda expression.

*It's an interface with only one abstract method

Lambda Expression enables method argument to treat functionality. It let you create an instance more compactly.

Inside Lambda expression, it is not allowed to change variables. 


여러줄의 코드를 메서드에 넣을 때 사용하는 개념. 

functional interface (한개의 메서드만 가지는 클래스) 일때만 람다식을 사용할 수 있다.

오버라이딩으로 다른 type의 argument를 받을 때는 data type을 반드시 명시해줘야한다.





Before Lambda Example code 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//When you write code inside another code, use Interface
interface Say{
    void something();
}
 
class Person{
    public void greeting(Say line){
        line.something();
    }
}
 
 public class Main{
    public static void main(String[] args) {
 
        //before Lambda
        Person p = new Person();
        p.greeting(new Say(){
            @Override
            public void something() {
                System.out.println("Person is p");
            }
        });
    }
 }
 
cs

 


우선, 람다식으로 구현할 Interface가 필요하다.

람다식이 나오기 전에는 new Say(){ } 식으로 객체를 생성하고 중괄호를 열어서 익명클래스로 새로운 코드를 삽입해야했다.

람다식으로는 위의 객체생성하는 부분을 삭제하고 () -> { } 으로만 선언해도 같은 결과를 가질 수 있다.

int a라는 매개변수를 가질 때에는 datatype 이나 ()를 적을 필요없이 a -> {} 라고 간단히 나타낼 수 있으나

매개변수가 2개 이상일 때에는 (a,b) -> { } 다시 괄호를 붙여야 한다.

overriding 으로 같은 이름의 메서드가 2개 이상일 경우 반드시 사용하고자하는 메서드의 datatype을 명시해줘야한다.

람다식안에서의 변수의 변경은 허용되지 않는다.




Lambda Example code

interface Say{
void something(int a, int b); //Functional Interface
}

interface Hello{
void something(String a, String b);
}

class Person{
public void greeting(Say line){
line.something(3,5);
}
//Overloading - same method name with difference parameters
public void greeting(Hello line){
line.something("Hello","World");
}
}

public class Main{
public static void main(String[] args) {

//before Lambda
Person p = new Person();
p.greeting(new Say(){
@Override
public void something(int a,int b) {
System.out.println("Before Lambda " + a + ", " + b);
}
});

System.out.println("==============");

//After Lambda
p.greeting( (int a,int b) -> {
System.out.println("Thank you Lambda. Values are " + a + ", " + b);
});

p.greeting( (String a, String b)-> {
System.out.println("Strings are " + a + ", " + b);
});
}
}



Result

Before Lambda 3, 5
==============
Thank you Lambda. Values are 3, 5
Strings are Hello, World


Reference

https://www.youtube.com/watch?v=foC6t8dZHls&t=24s

'JAVA' 카테고리의 다른 글

Difference between Collection and Collections in Java  (0) 2019.02.26
How to convert Arrays to List  (0) 2019.02.26
compareTo method in Java  (0) 2019.02.21
Reference Data Type in Java  (0) 2019.02.20
Anonymous class in Java  (0) 2019.02.20