2019λ…„ 7μ›” 4일 λͺ©μš”일

λžŒλ‹€μ‹ (Lambda, 𝝀) 예제


Java8μ—μ„œ μƒˆλ‘­κ²Œ μΆ”κ°€ 된 κΈ°λŠ₯. κ°„λ‹¨ν•˜κ²Œ μš”μ•½ ν•˜λ©΄ λ©”μ†Œλ“œλ₯Ό κ°„λ‹¨νžˆ κΈ°μˆ ν•˜λŠ” 기법
ꡬ문 Lambda식
(μžλ£Œν˜• 인수, ...) -> { ... μž„μ˜μ˜ 처리 ...}

κ΅¬ν˜„ν•  μΈν„°νŽ˜μ΄μŠ€ μ½”λ“œ
package project.lambda;

public interface InterfaceExample{
    public abstract void exampleMethod(String name);
}

κΈ°λ³Έ λžŒλ‹€ 예제
package project.lambda;
/**
* λžŒλ‹€μ‹ 예제 μž…λ‹ˆλ‹€.
*/
public class LambdaExample{
   
    public static void main(String...args){
       // 처리λ₯Ό λžŒλ‹€μ‹μœΌλ‘œ κ΅¬ν˜„ 함.
        InterfaceExample lambda = (String name) -> {
            System.out.println("이것이 λ°”λ‘œ λžŒλ‹€("+name+")μž…λ‹ˆλ‹€");
        };
        
        // λžŒλ‹€μ‹μ„ μ‹€ν–‰ ν•©λ‹ˆλ‹€.
        lambda.exampleMethod("Lambda ^^");
    }
}

μ΄μ „μ—λŠ” 읡λͺ…(anonymouse) 클래슀둜 처리 함
package project.lambda;

/**
* λžŒλ‹€μ‹ 이전에 λžŒλ‹€μ‹ 처리λ₯Ό λŒ€μ‹  ν–ˆλ˜ 읡λͺ…ν΄λž˜μŠ€(anonymouse) 방식
* 의 예제 μž…λ‹ˆλ‹€.
*/
public class AnonymouseExample{
    public static void main(String... args){
        // 읡λͺ…ν΄λž˜μŠ€λ₯Ό μ΄μš©ν•΄μ„œ κ΅¬ν˜„ 함
        InterfaceExample anonymouse = new InterfaceExample(){
            public void exampleMethod(String name){
                System.out.println("이것이 λ°”λ‘œ 읡λͺ…ν΄λž˜μŠ€("+name+") μž…λ‹ˆλ‹€");
            }
        };
        
        // 읡λͺ…ν΄λž˜μŠ€ λ³€μˆ˜ μ‹€ν–‰
        anonymouse.exampleMethod("anonymouse");
    }
}

λ°˜ν™˜ κ°’μ˜ Lambda μ˜ˆμ œλ“€
package project.lambda;

/**
* λžŒλ‹€μ‹ λ°˜ν™˜μ‹ 예제 μž…λ‹ˆλ‹€.
*/
public class LambdaReturnValueExample{
    
    public static void main(String...args){
       // 처리λ₯Ό λžŒλ‹€μ‹μœΌλ‘œ κ΅¬ν˜„ 함.
        InterfaceReturnValue lambda = (String name) -> {
            return "("+name+")";
        };
        
        // λžŒλ‹€μ‹μ„ μ‹€ν–‰ ν•©λ‹ˆλ‹€.
        System.out.println("이것이 λ°”λ‘œ λžŒλ‹€μ‹"+
                           lambda.exampleMethod("Lambda ^^")+" μž…λ‹ˆλ‹€");
        
        // νŒŒλΌλ―Έν„° νƒ€μž…μ„ μƒλž΅ν•˜κΈ°
        lambda = (name) -> { return "<"+name+">";};
        System.out.println("이것이 λ°”λ‘œ ν˜•μƒλž΅ λžŒλ‹€μ‹"+
                           lambda.exampleMethod("Lambda ^^")+" μž…λ‹ˆλ‹€");
        
        // νŒŒλΌλ―Έν„°κ°€ ν•œ 개인 경우 κ΄„ν˜Έ μƒλž΅ν•˜κΈ°
        lambda = name -> { return "{"+name+"}";};
        System.out.println("이것이 λ°”λ‘œ κ΄„ν˜Έμƒλž΅ λžŒλ‹€μ‹"+
                           lambda.exampleMethod("Lambda ^^")+" μž…λ‹ˆλ‹€");
        
        // return 문만 μžˆλŠ” 경우의 μƒλž΅
        lambda = name -> "["+name+"]";
        System.out.println("이것이 λ°”λ‘œ returnλ¬Έ μƒλž΅ λžŒλ‹€μ‹"+
                           lambda.exampleMethod("Lambda ^^")+" μž…λ‹ˆλ‹€");
        
    }
}
/**
* λ°˜ν™˜κ°’μ„ κ°–λŠ” μΈν„°νŽ˜μ΄μŠ€ μž„.
*/
interface InterfaceReturnValue{
    public String exampleMethod(String name);
}

λŒ“κΈ€ μ—†μŒ: