[Java] 람다 표현식: 기초부터 고급까지
자바 8에서 도입된 람다 표현식(Lambda Expression)은 함수형 프로그래밍 기능을 제공하며, 코드의 간결성과 가독성을 크게 향상시킵니다. 이번 포스트에서는 람다 표현식의 기초부터 고급 활용법까지 자세히 살펴보겠습니다.
- #Java
이 시리즈의 다른 글 Java · 4/4
- 1 [Java] ArrayList
- 2 [Java] 예외처리
- 3 [Java] 컬렉션 프레임워크
- 4 [Java] 람다 표현식: 기초부터 고급까지
자바 8에서 도입된 람다 표현식(Lambda Expression)은 함수형 프로그래밍 기능을 제공하며, 코드의 간결성과 가독성을 크게 향상시킵니다. 이번 포스트에서는 람다 표현식의 기초부터 고급 활용법까지 자세히 살펴보겠습니다.
1. 람다 표현식이란?
람다 표현식은 익명 함수(anonymous function)를 나타내는 간결한 방법입니다. 람다 표현식을 사용하면 작은 코드 조각을 함수처럼 작성할 수 있습니다. 람다 표현식의 기본 형식은 다음과 같습니다:
(parameters) -> expression
또는 여러 줄의 코드가 있을 경우 중괄호를 사용하여 작성할 수 있습니다:
(parameters) -> {
// code block
}
2. 람다 표현식의 기본 사용법
람다 표현식을 이해하기 위해 간단한 예제를 살펴보겠습니다. 먼저 람다 표현식을 사용하지 않은 전통적인 방식입니다:
import java.util.Arrays;
import java.util.List;
public class LambdaExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Jane", "Jack", "Doe");
// 전통적인 방식의 반복문
for (String name : names) {
System.out.println(name);
}
}
}
위 코드를 람다 표현식을 사용하여 간단하게 만들 수 있습니다:
import java.util.Arrays;
import java.util.List;
public class LambdaExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Jane", "Jack", "Doe");
// 람다 표현식을 사용한 반복문
names.forEach(name -> System.out.println(name));
}
}
3. 함수형 인터페이스
람다 표현식은 함수형 인터페이스(functional interface)와 함께 사용됩니다. 함수형 인터페이스는 하나의 추상 메서드만을 갖는 인터페이스입니다. 예를 들어, Runnable 인터페이스는 함수형 인터페이스입니다:
@FunctionalInterface
public interface Runnable {
void run();
}
람다 표현식을 사용하여 Runnable 인터페이스를 구현할 수 있습니다:
Runnable r = () -> System.out.println("Running in a thread");
4. 주요 함수형 인터페이스
자바에서는 여러 가지 기본 함수형 인터페이스를 제공하며, 이를 이용하여 다양한 람다 표현식을 작성할 수 있습니다. 주요 함수형 인터페이스는 다음과 같습니다:
Predicate<T>: 인수를 받아서 boolean 값을 반환하는 함수.test메서드를 가집니다.Function<T, R>: 인수를 받아서 다른 객체를 반환하는 함수.apply메서드를 가집니다.Consumer<T>: 인수를 받아서 사용하고 반환값이 없는 함수.accept메서드를 가집니다.Supplier<T>: 인수를 받지 않고 객체를 반환하는 함수.get메서드를 가집니다.
예제를 통해 각 함수형 인터페이스의 사용법을 살펴보겠습니다:
Predicate 예제
import java.util.function.Predicate;
public class PredicateExample {
public static void main(String[] args) {
Predicate<Integer> isEven = x -> x % 2 == 0;
System.out.println(isEven.test(4)); // true
System.out.println(isEven.test(7)); // false
}
}
Function 예제
import java.util.function.Function;
public class FunctionExample {
public static void main(String[] args) {
Function<String, Integer> lengthFunction = String::length;
System.out.println(lengthFunction.apply("Hello")); // 5
System.out.println(lengthFunction.apply("Lambda")); // 6
}
}
Consumer 예제
import java.util.function.Consumer;
public class ConsumerExample {
public static void main(String[] args) {
Consumer<String> printConsumer = System.out::println;
printConsumer.accept("Hello, World!"); // Hello, World!
}
}
Supplier 예제
import java.util.function.Supplier;
public class SupplierExample {
public static void main(String[] args) {
Supplier<Double> randomSupplier = Math::random;
System.out.println(randomSupplier.get()); // 0.123456789 (랜덤 값)
}
}
5. 고급 활용: 스트림 API와 람다 표현식
자바 8에서는 람다 표현식과 함께 스트림 API가 도입되어 데이터 처리 작업을 더욱 쉽게 할 수 있습니다. 스트림 API는 컬렉션 데이터를 처리하는 데 매우 유용하며, 람다 표현식과 함께 사용하여 복잡한 작업도 간결하게 표현할 수 있습니다.
다음은 스트림 API와 람다 표현식을 사용한 예제입니다:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Jane", "Jack", "Doe");
// 필터링과 맵핑을 사용한 스트림 처리
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("J"))
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(filteredNames); // [JOHN, JANE, JACK]
}
}
6. 고차 함수와 커링(Currying)
람다 표현식을 활용하여 고차 함수(higher-order function)를 만들 수 있습니다. 고차 함수는 함수를 인수로 받거나 함수를 반환하는 함수입니다. 또한 커링(Currying)은 여러 인수를 받는 함수를 여러 개의 단일 인수를 받는 함수로 변환하는 기법입니다.
고차 함수 예제
import java.util.function.Function;
public class HigherOrderFunctionExample {
public static void main(String[] args) {
Function<Integer, Function<Integer, Integer>> add = x -> y -> x + y;
Function<Integer, Integer> add5 = add.apply(5);
System.out.println(add5.apply(3)); // 8
}
}
커링 예제
import java.util.function.Function;
public class CurryingExample {
public static void main(String[] args) {
Function<Integer, Function<Integer, Function<Integer, Integer>>> curryAdd =
x -> y -> z -> x + y + z;
Function<Integer, Function<Integer, Integer>> add5 = curryAdd.apply(5);
Function<Integer, Integer> add5And3 = add5.apply(3);
System.out.println(add5And3.apply(2)); // 10
}
}
7. 람다 표현식과 예외 처리
람다 표현식에서 체크 예외를 처리하는 것은 약간의 주의가 필요합니다. 보통 람다 표현식 내에서 예외를 처리할 수 있도록 별도의 메서드를 작성합니다. 다음은 람다 표현식에서 체크 예외를 처리하는 방법입니다:
import java.util.function.Consumer;
public class LambdaExceptionHandling {
public static void main(String[] args) {
Consumer<String> printConsumer = wrapConsumer(LambdaExceptionHandling::printWithException);
printConsumer.accept("Hello");
}
static void printWithException(String input) throws Exception {
if (input.isEmpty()) {
throw new Exception("Empty input");
}
System.out.println(input);
}
static <T> Consumer<T> wrapConsumer(ConsumerWithException<T> consumer) {
return i -> {
try {
consumer.accept(i);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
@FunctionalInterface
interface ConsumerWithException<T> {
void accept(T t) throws Exception;
}
}
물론입니다. 자바 람다 표현식에 대한 설명을 보완하기 위해 몇 가지 추가 주제를 다루겠습니다. 이 주제들은 람다 표현식을 더 깊이 이해하고 실제 개발에 적용하는 데 유용할 것입니다.
9. 메서드 참조(Method References)
메서드 참조는 람다 표현식을 더욱 간결하게 만드는 기능입니다. 이미 존재하는 메서드를 참조하여 람다 표현식을 대신할 수 있습니다. 메서드 참조의 주요 유형은 다음과 같습니다:
- 정적 메서드 참조
- 인스턴스 메서드 참조
- 특정 객체의 인스턴스 메서드 참조
- 생성자 참조
정적 메서드 참조
import java.util.function.Function;
public class MethodReferenceExample {
public static void main(String[] args) {
Function<String, Integer> stringToInteger = Integer::parseInt;
Integer result = stringToInteger.apply("123");
System.out.println(result); // 123
}
}
인스턴스 메서드 참조
import java.util.function.BiPredicate;
public class InstanceMethodReferenceExample {
public static void main(String[] args) {
BiPredicate<String, String> equalsMethod = String::equals;
boolean result = equalsMethod.test("test", "test");
System.out.println(result); // true
}
}
특정 객체의 인스턴스 메서드 참조
import java.util.function.Consumer;
public class SpecificInstanceMethodReferenceExample {
public static void main(String[] args) {
Consumer<String> printConsumer = System.out::println;
printConsumer.accept("Hello, World!"); // Hello, World!
}
}
생성자 참조
import java.util.function.Supplier;
public class ConstructorReferenceExample {
public static void main(String[] args) {
Supplier<StringBuilder> stringBuilderSupplier = StringBuilder::new;
StringBuilder stringBuilder = stringBuilderSupplier.get();
stringBuilder.append("Hello, Constructor Reference!");
System.out.println(stringBuilder.toString()); // Hello, Constructor Reference!
}
}
10. 변수 캡처(Variable Capture)
람다 표현식은 람다 내부에서 사용되는 외부 변수들을 캡처할 수 있습니다. 그러나 람다 표현식에서 캡처되는 변수는 final 또는 실질적으로 final 이어야 합니다. 이를 통해 람다 표현식에서의 변수 사용 규칙을 이해할 수 있습니다.
예제
public class VariableCaptureExample {
public static void main(String[] args) {
final int num = 10;
Runnable r = () -> {
System.out.println(num); // 10
};
r.run();
}
}
num 변수는 final로 선언되었기 때문에 람다 표현식 내부에서 사용할 수 있습니다. final로 선언되지 않더라도 변경되지 않으면 사용할 수 있습니다.
public class VariableCaptureExample {
public static void main(String[] args) {
int num = 10;
Runnable r = () -> {
System.out.println(num); // 10
};
r.run();
}
}
그러나 아래와 같이 변수 값을 변경하면 컴파일 오류가 발생합니다:
public class VariableCaptureExample {
public static void main(String[] args) {
int num = 10;
Runnable r = () -> {
// num = 15; // 컴파일 오류
System.out.println(num);
};
r.run();
}
}
11. 디폴트 메서드와 정적 메서드를 가지는 인터페이스
람다 표현식과 함께 자바 8에서는 인터페이스에 디폴트 메서드(default methods)와 정적 메서드(static methods)를 추가할 수 있게 되었습니다. 이를 통해 인터페이스를 더 유연하게 사용할 수 있습니다.
디폴트 메서드
public interface MyInterface {
void abstractMethod();
default void defaultMethod() {
System.out.println("This is a default method");
}
}
public class MyClass implements MyInterface {
public void abstractMethod() {
System.out.println("This is the abstract method implementation");
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.abstractMethod(); // This is the abstract method implementation
obj.defaultMethod(); // This is a default method
}
}
정적 메서드
public interface MyInterface {
void abstractMethod();
static void staticMethod() {
System.out.println("This is a static method");
}
}
public class MyClass implements MyInterface {
public void abstractMethod() {
System.out.println("This is the abstract method implementation");
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.abstractMethod(); // This is the abstract method implementation
// 정적 메서드는 인터페이스명으로 호출
MyInterface.staticMethod(); // This is a static method
}
}
12. 람다 표현식과 동시성
람다 표현식은 동시성 프로그래밍에서도 유용하게 사용할 수 있습니다. 특히, 병렬 스트림(parallel stream)과 함께 사용하면 병렬 처리를 간단하게 구현할 수 있습니다.
병렬 스트림 예제
import java.util.Arrays;
import java.util.List;
public class ParallelStreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 병렬 스트림을 사용하여 병렬 처리
int sum = numbers.parallelStream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum: " + sum); // Sum: 55
}
}
13. 자바의 람다 표현식과 다른 언어와의 비교
자바의 람다 표현식을 다른 언어의 람다와 비교해보면, 자바스크립트, 파이썬, C# 등 여러 언어에서의 람다 표현식과의 차이점을 이해할 수 있습니다.
자바스크립트와의 비교
자바스크립트에서도 람다 표현식(화살표 함수)을 지원합니다. 자바와의 주요 차이점은 스코프 처리 방식입니다.
const add = (x, y) => x + y;
console.log(add(2, 3)); // 5
파이썬과의 비교
파이썬의 람다 표현식은 간단한 익명 함수 작성에 사용됩니다.
add = lambda x, y: x + y
print(add(2, 3)) # 5
C#과의 비교
C#의 람다 표현식은 자바와 유사하지만, 더욱 강력한 기능들을 제공합니다.
Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(2, 3)); // 5
14. 람다 표현식의 장단점
람다 표현식을 사용하는 것의 장단점을 이해하는 것도 중요합니다.
장점
- 코드 간결성: 짧고 간결한 코드로 가독성을 높일 수 있습니다.
- 함수형 프로그래밍 지원: 함수형 프로그래밍 패러다임을 지원합니다.
- 병렬 처리 용이: 스트림 API와 함께 사용하여 병렬 처리를 간단하게 구현할 수 있습니다.
단점
- 디버깅 어려움: 람다 표현식은 익명 함수이므로 디버깅이 어려울 수 있습니다.
- 복잡성 증가: 복잡한 람다 표현식은 오히려 가독성을 떨어뜨릴 수 있습니다.
- 성능 이슈: 잘못 사용하면 성능 문제를 야기할 수 있습니다.
이번 포스트에서는 자바 람다 표현식의 기초부터 고급 활용법까지 다양한 주제를 다루었습니다. 람다 표현식을 이해하고 활용하는 것은 자바 프로그래머로서 중요한 스킬입니다. 이를 통해 코드의 간결성, 가독성, 효율성을 높일 수 있습니다. 람다 표현식을 적극적으로 활용하여 더욱 효과적인 자바 프로그래밍을 해보시기 바랍니다.
이 글은 원래 Velog에 2024-07-17에 올린 글입니다. 원문: [Java] 람다 표현식: 기초부터 고급까지
마지막 수정: