본문 바로가기

Programming/자바

자바 재정리 - 람다식

: 익명 함수 생성하기 위한 식

=> 코드 간결화

 

 

 

  • ex
public class ThreadEx5 {

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
        
            @Override
            public void run() {
                Toolkit toolkit = Toolkit.getDefaultToolkit(); 
                for (int i=1;i<=5;i++) {
                    try {
                        toolkit.beep(); 
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                    }  
                }
            }
        
        });
        
        thread.start();
        
    }

}


=>람다식


    public static void main(String[] args) {
        
        Thread thread = new Thread(()-> { //람다식 이용 (Runnable 구현 익명 객체)
            Toolkit toolkit = Toolkit.getDefaultToolkit(); 
            for (int i=1;i<=5;i++) {
                try {
                    toolkit.beep(); 
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                } 
            }
        });
        thread.start();
    
        for (int i=1;i<=5;i++) {
            System.out.println("띵!!");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
        }  
    }​

 

 

 

  • 기본 문법
@FunctionalInterface
public interface Calculator {

    //추상 메소드 1
    public int hap(int num1, int num2);
    
}


public class CalculatorEx1 {

    public static void main(String[] args) {
    
        Calculator cal;  
        
        //람다식 이용 익명 객체 구현
        cal =(a,b)-> {
            int result = a+b;
            return result;
        };
        System.out.println("두 수의 합 : "+cal.hap(3, 2));
        
        //람다식 이용 (실행할 명령문이 한 줄일 때)
        cal =(a,b)-> {return a+b;};
        System.out.println("두 수의 합 = "+cal.hap(4, 2));
        
        //람다식 이용 (실행할 명령문이 한 줄 => 리턴문, 중괄호 생략 가능)
        cal =(a,b)-> a+b;
        System.out.println("두 수의 합 = "+cal.hap(4, 3));
        
        //람다식 이용 (내부 메서드 호출해서 처리)
        cal =(a,b)-> sum(a,b);
        System.out.println("두 수의 합 : "+cal.hap(3, 6));
        
    }
    
    public static int sum(int num1, int num2) {
        return num1+num2;
    }
    
}
//
두 수의 합 : 5
두 수의 합 = 6
두 수의 합 = 7
두 수의 합 : 9

 

 

 

 

타겟 타입, 함수적 인터페이스
인터페이스 변수 = 람다식;

 

람다식 대입될 인터페이스 => 람다식의 타겟 타입 

 

함수적 인터페이스 (@FunctionalInterface) : 단 하나의 추상메소드 선언해야 함 (람다식 조건)

 

 

 

  • 매개변수 X, 리턴값 X
public interface Person {

    //추상메서드
    public void info();
    
}

public class PersonEx1 {

    public static void main(String[] args) {
        //인터페이스 객체 필드 선언, 익명으로 객체 구현
        Person gildong = new Person() {
            @Override
            public void info() {
                System.out.println("나는 종로에 사는 홍길동입니다.");
                System.out.println("자바 웹개발을 배우는 중입니다.");
            }
        };
        gildong.info();
        
        //람다식 표현1
        Person chanho=()-> {
            System.out.println("나는 영등포에 사는 찬호입니다.");
            System.out.println("자바 웹개발을 배우는 중입니다.");
        }; //info 메소드 작성 안 돼도 인식 => 함수적 인터페이스 -> 메소드 하나라서
        chanho.info();  
        
        //람다식 표현2 코드 한 줄 => 중괄호 필요 X
        Person minho=()-> System.out.println("나는 강남에 사는 민호입니다.");
        minho.info();
        
    }

}
 

 

 
  • 매개변수 O, 리턴 X
@FunctionalInterface
public interface Person2 {

    //추상메서드
    public void info(int age);
    
}


public class Person2Ex1 {

    public static void main(String[] args) {
        //매개 변수 있는 람다식
        Person2 chanho;
        
        chanho =(age)-> {
            int myAge = age+1;
            System.out.println("내 나이는 "+myAge+"세입니다.");
        };
        chanho.info(27);
        
        chanho=age-> System.out.println("내 나이는 "+(age+1)+"세입니다.");    
        //한 줄 -> 매개변수 괄호 없애도 됨
        chanho.info(35);
        
    }

}
//
내 나이는 28세입니다.
내 나이는 36세입니다.

 

 

 

  • 매개변수 O, 리턴 O
@FunctionalInterface
public interface Person3 {
    
     public String info(double height, double weight);
     
}


public class Person3Ex1 {

    public static void main(String[] args) {
        
        Person3 younghee =(h,w)-> {   //매개변수 이름은 개발자 자유
            String result = "내 키는 "+h+"cm이고 몸무게는 "+w+"kg입니다.";
            return result;
        };
        System.out.println(younghee.info(168, 47));
    }

}
//
내 키는 168.0cm이고 몸무게는 47.0kg입니다.

 

 

 

  • Supplier 함수적 인터페이스 (매개변수 X, 리턴 O)
import java.util.function.IntSupplier;

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

        IntSupplier supplier =()-> { //리턴값 필요
            int num = (int) ((Math.random()*6)+1);
            return num;
        };
        
        System.out.println("주사위 눈의 수 : "+supplier.getAsInt());  //추상메서드
        
    }    

}​

 

 

 

 

 

 

 

 

 

 

 

 

 

'Programming > 자바' 카테고리의 다른 글

자바 재정리 - 컬렉션 프레임워크  (0) 2022.09.09
자바 재정리 - 제네릭  (0) 2022.09.08
자바 재정리 - 멀티 스레드  (0) 2022.09.07
자바 재정리 - API  (0) 2022.09.05
자바 재정리 - 예외 처리  (0) 2022.08.26