SSAFY

[Java] 람다식

hellosonic 2024. 8. 20. 16:17

✅ 람다식이란?

  • 함수형 프로그래밍이란 함수를 정의하고 이 함수를 데이터 처리부로 보내 데이터를 처리하는 기법을 말한다.
  • 자바는 함수형 프로그래밍을 위해 Java 8부터 람다식을 지원한다.
  • 자바는 람다식을 익명 구현 객체로 변환한다.
// Calculable 인터페이스
public interface Calculable {
	void calculate(int x, int y);
}

// Calculable 인터페이스의 익명 구현 객체
new Calculable() {
	@Override
    public void calculate(int x, int y) {처리 내용};
}

// 람다식
(x, y) -> {처리 내용};
  • 인터페이스의 익명 구현 객체를 람다식으로 표현하려면 인터페이스가 단 하나의 추상 메서드만 가져야 한다.
// 인터페이스가 두 개의 추상메서드를 가지므로 람다식으로 표현할 수 없다.
public interface RemoteControl {
	void turnOn();
    void turnOff();
}
  • 인터페이스가 단 하나의 추상 메서드를 가질 때, 이를 함수형 인터페이스라고 한다.

 

 

✅ 매개 변수가 없는 람다식

  • 함수형 인터페이스의 추상 메서드에 매개변수가 없을 경우
@FunctionalInterface
public interface Workable {
	void work();
}

public class Person {
	public void action(Workable workable) {
    	workable.work();
    }
}

public class LambdaExample {
	public static void main(String[] args) {
    	Person person = new Person();
        
        person.action(() -> {
        	System.out.println("출근완");
        });
    }
}
public class Button {
	@FunctionalInterface
    public static interface ClickListener {
    	// 추상 메서드
    	void onClick();
    }
    
    // 필드
    private ClickListener clickListener;
    
    // 메서드
    public void setClickListener(ClickListener clickListener) {
    	this.clickListener = clickListener;
    }
    
    public void click() {
    	this.clickListener.onClick();
    }
}

public class ButtonExample {
	public static void main(String[] args) {
    	Button btnOk = new Button();
        
        btnOk.setClickListener(() -> {
        	System.out.println("OK 버튼을 클릭했습니다.");
        });
        
        btnOk.click();
    }
}

 

 

 

✅ 매개 변수가 있는 람다식

@FunctionalInterface
public interface Workable {
	void work(String name, String job);
}

@FunctionalInterface
public interface Speakable {
	void speak(String content);
}

public class Person {
	public void action1(Workable workable) {
    	workable.work("홍길동", "프로그래밍");
    }
}

public LambdaExample {
	public static void main(String[] args) {
    	Person person = new Person();
        
        Person.action1((name, job) -> {
        	System.out.print(name);
            System.out.print(job);
        });
    }
}

 

 

✅ 리턴 값이 있는 람다식

  • return 문 하나만 있을 경우에는 중괄호와 함께 return 키워드를 생략할 수 있다.
@FunctionalInterface
public interface Calcuable {
	double calc(double x, double y);
}

public class Person {
	public void action(Calcuable calcuable) {
    	double result = calcuable.calc(10, 4);
        System.out.println("결과: " + result);
    }
}

public class LambdaExample {
	public static void main(String[] args) {
    	Person person = new Person();
        
        person.action((x, y) -> {
        	double result = x + y;
            return result;
        })
        person.action((x, y) -> (x + y));
    	person.action((x, y) -> sum(x, y));
    }
    
    public static double sum(double x, double y) {
    	return (x + y);
    }
}

 

 

 

✅ 메서드 참조

📌 정적 메서드와 인스턴스 메서드 참조

  • 정적 메서드를 참조할 경우 - 클래스 :: 메서드
  • 인스턴스 메서드일 경우 - 참조변수 :: 메서드