함수를 일급 객체로 다루고, 상태 변경 없이(불변성), 순수 함수들을 조합해 프로그램을 만드는 프로그래밍 패러다임
순수 함수와 불변성을 기반으로 부작용 없는 함수들을 조합해 프로그램을 만드는 방식
기존에는 "어떻게 할 지(How)" 하나하나 명령을 작성했다면, 함수형은 "무엇을 할 지(What)" 함수 중심으로 간결하게 표현함
map, filter, reduce 같은 함수 사용장점
단점
명령형 방식
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
List<Integer> result = new ArrayList<>();
for(int n: numbers) {
if (n%2 == 0) {
result.add(n*n);
}
}
System.out.println(result); // [4, 16]
함수형 방식
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
List<Integer> result = numbers.stream()
.filter(n -> n%2 == 0)
.map(n -> n*n)
.collect(Collectors.toList());
System.out.println(result); // [4, 16]
차이
filter()로 조건에 맞는 것만 고르고map()으로 변형해서collect()로 최종 결과를 모음for문 없이 '무엇을 할 지' 명확히 표현함Function<Integer, Integer> square = x -> x * x;
int result = square.apply(5); // 25
Function<T, R>: 입력 T → 출력 RPredicate<T>: 조건 (true/false)Consumer<T>: 소비 (출력 등)Supplier<T>: 공급 (값 제공)List<Integer> list = List.of(10, 15, 20, 25, 30);
Predicate<Integer> isDivisible5 = x -> x%5 == 0;
List.stream()
.filter(isDivisible5)
.forEach(System.out::println); // 10 15 20 25 30
Java8부터 함수형 프로그래밍 가능
코드를 더 짧고 직관적으로, 버그를 줄이는 방식으로 작성할 수 있음.
stream, lambda, Function, Predicate 등을 사용함
| 기존 방식 | 함수형 스타일 |
|---|---|
for로 조건 검사 | filter() 사용 |
| 직접 리스트 add | map()으로 처리 후 collect |
| 하나하나 변수 선언 | 함수나 람다로 간결하게 표현 |