SeouliteLab

[Java/자바] Function 합성: compose() 메서드로 함수 합성하기 본문

프로그래밍

[Java/자바] Function 합성: compose() 메서드로 함수 합성하기

Seoulite Lab 2024. 3. 13. 14:30

Java에서는 Function 인터페이스의 compose() 메서드를 사용하여 함수를 합성할 수 있습니다. compose() 메서드를 사용하면 함수를 역순으로 합성하여 더욱 유연하게 데이터 변환을 할 수 있습니다.

예제 1: 두 개의 Function 합성하기

두 개의 Function을 compose() 메서드를 사용하여 합성하는 예제입니다. 첫 번째 Function이 먼저 적용되고, 그 결과가 두 번째 Function의 입력으로 전달됩니다.

import java.util.function.Function;

public class FunctionComposition {
    public static void main(String[] args) {
        Function<Integer, Integer> multiplyByTwo = n -> n * 2;
        Function<Integer, Integer> addThree = n -> n + 3;

        Function<Integer, Integer> multiplyByTwoThenAddThree = multiplyByTwo.compose(addThree);
        int result = multiplyByTwoThenAddThree.apply(5);
        System.out.println("결과: " + result); // 출력 결과: 결과: 13 ((5 * 2) + 3)
    }
}

예제 2: 세 개의 Function 합성하기

세 개의 Function을 compose() 메서드를 사용하여 합성하는 예제입니다. compose() 메서드는 연속적으로 적용할 수 있습니다.

import java.util.function.Function;

public class FunctionComposition {
    public static void main(String[] args) {
        Function<Integer, Integer> addTwo = n -> n + 2;
        Function<Integer, Integer> multiplyByThree = n -> n * 3;
        Function<Integer, Integer> subtractFive = n -> n - 5;

        Function<Integer, Integer> addTwoThenMultiplyByThreeThenSubtractFive = addTwo.compose(multiplyByThree).compose(subtractFive);
        int result = addTwoThenMultiplyByThreeThenSubtractFive.apply(10);
        System.out.println("결과: " + result); // 출력 결과: 결과: 17 (((10 - 5) * 3) + 2)
    }
}

예제 3: 람다 표현식을 사용하여 Function 합성하기

람다 표현식을 사용하여 Function을 직접 정의하여 합성하는 예제입니다.

import java.util.function.Function;

public class FunctionComposition {
    public static void main(String[] args) {
        Function<Integer, Integer> multiplyByTwoThenAddOne = ((Function<Integer, Integer>) n -> n * 2)
                .compose(n -> n + 1);

        int result = multiplyByTwoThenAddOne.apply(7);
        System.out.println("결과: " + result); // 출력 결과: 결과: 16 ((7 + 1) * 2)
    }
}