반응형
자바 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;
}
}
결론:
함수형 인터페이스와 람다 표현식을 사용하면 코드가 간결하고 가독성이 높아지며, 함수형 프로그래밍의 장점을 활용할 수 있습니다. 이를 통해 유지보수성이 향상되고 코드 작성이 훨씬 즐겁고 효율적으로 이루어집니다.
반응형
'Programing > JAVA' 카테고리의 다른 글
Java 애플리케이션을 데몬으로 실행하기: Apache Commons Daemon과 jsvc 사용법 (0) | 2024.06.27 |
---|---|
Apache Commons Daemon으로 데몬 서비스 구현하기 (0) | 2024.06.27 |
Java에서 파일 경로를 사용하여 File 객체 생성하기: 다양한 접근법 (0) | 2023.11.15 |
Java로 특정 폴더 내의 모든 내용 삭제하기 (0) | 2023.11.15 |
java JSON 파싱 예제 (0) | 2023.09.21 |