본문으로 바로가기
반응형

자바 8부터 도입된 함수형 프로그래밍의 핵심인 함수형 인터페이스와 람다 표현식을 통해 코드를 간결하게 작성하는 방법을 살펴봅니다. 고전적인 방식에서의 코드 작성과 비교하여 얼마나 편리하고 간결해졌는지 확인해보세요.

내용:

1. 함수형 인터페이스 정의:

@FunctionalInterface
interface Calculator {
    int calculate(int a, int b);
}

2. 람다 표현식으로 덧셈 구현:

Calculator addition = (a, b) -> a + b;

3. 람다 표현식으로 뺄셈 구현:

Calculator subtraction = (a, b) -> a - b;

4. 함수형 인터페이스 활용:

public static void main(String[] args) {
    int result1 = performOperation(10, 5, addition); // 10 + 5
    int result2 = performOperation(10, 5, subtraction); // 10 - 5
    System.out.println("Result1: " + result1);
    System.out.println("Result2: " + result2);
}

private static int performOperation(int a, int b, Calculator calculator) {
    return calculator.calculate(a, b);
}

5. 고전적인 방식과의 비교:

interface ClassicCalculator {
    int add(int a, int b);
    int subtract(int a, int b);
}

public static void main(String[] args) {
    ClassicCalculator classicCalculator = new ClassicCalculatorImpl();
    int result1 = classicCalculator.add(10, 5); // 10 + 5
    int result2 = classicCalculator.subtract(10, 5); // 10 - 5
    System.out.println("Result1: " + result1);
    System.out.println("Result2: " + result2);
}

static class ClassicCalculatorImpl implements ClassicCalculator {
    @Override
    public int add(int a, int b) {
        return a + b;
    }

    @Override
    public int subtract(int a, int b) {
        return a - b;
    }
}

결론:
함수형 인터페이스와 람다 표현식을 사용하면 코드가 간결하고 가독성이 높아지며, 함수형 프로그래밍의 장점을 활용할 수 있습니다. 이를 통해 유지보수성이 향상되고 코드 작성이 훨씬 즐겁고 효율적으로 이루어집니다.

반응형