Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 수수료
- 심장질환
- 뇌출혈
- 납입
- 파이썬
- 추가납입
- 보험료
- 자바스크립트
- 급성심근경색증
- 사망
- 가입
- 리스트
- 변환
- 보험
- jQuery
- python
- 프로그래밍
- 문자열
- javascript
- 특약
- 웹개발
- 인출수수료
- 교보
- Vue.js
- PythonProgramming
- 교보생명
- Java
- 중도인출
- 코딩
- 프론트엔드
Archives
- Today
- Total
SeouliteLab
[Java/자바] Function 합성: compose() 메서드로 함수 합성하기 본문
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)
}
}
'프로그래밍' 카테고리의 다른 글
[Java/자바] Spring RestTemplate 설정 방법 (0) | 2024.03.14 |
---|---|
[Java/자바] Spring RestTemplate을 활용한 웹 서비스 통신 (0) | 2024.03.14 |
[Java/자바] Function 연결: andThen()으로 다수의 Function 순차적 수행하기 (0) | 2024.03.13 |
[Java/자바] Function 예제: 입력을 받아 결과를 반환하는 함수 (0) | 2024.03.13 |
[Java/자바] BiFunction 연결: andThen() 메서드를 사용하여 BiFunction 순차 실행하기 (0) | 2024.03.13 |