본문으로 건너뛰기
Advertisement

스트림의 최종 연산 (Terminal Operations)

스트림 파이프라인의 가장 마지막 에 위치하여, 스트림의 요소를 소비(Consume)하고 최종 결과(데이터 개수, 컬렉션 객체, 단일 값 등)를 만들어냅니다. 최종 연산이 호출되는 순간 스트림 파이프라인의 중간 연산들이 일제히 실행되며 스트림은 닫히게 됩니다.

1. 출력: forEach

스트림의 각 요소에 대해 지정된 동작을 수행합니다. 디버깅 및 출력용으로 자주 사용됩니다.

List<String> members = Arrays.asList("Alice", "Bob", "Charlie");
members.stream().forEach(System.out::println);

2. 매칭 및 조건 검사: allMatch, anyMatch, noneMatch

스트림의 요소들이 조건에 맞는지 논리(Boolean) 여부를 판단합니다.

  • allMatch(Predicate): 모든 요소가 조건을 만족하면 true
  • anyMatch(Predicate): 하나라도 만족하면 true
  • noneMatch(Predicate): 모두 만족하지 않으면 true
List<Integer> scores = Arrays.asList(85, 90, 78, 92);

boolean hasFail = scores.stream().anyMatch(score -> score < 80); // true (78 있음)
boolean isAllPass = scores.stream().allMatch(score -> score >= 80); // false

3. 통계 및 누적: count, sum, reduce

  • count(), sum(), max(), min(), average(): 기본적인 통계 데이터를 구합니다. (sum() 등은 IntStream과 같은 기본형 스트림에서 제공됩니다.)
  • reduce(): 반복하며 스트림의 요소를 하나씩 줄여가며 단일 결과값을 만듭니다.
int[] numbers = {1, 2, 3, 4, 5};

int sum = Arrays.stream(numbers).sum(); // 15
long count = Arrays.stream(numbers).count(); // 5

// reduce를 사용한 누적 곱
int multiplied = Arrays.stream(numbers)
.reduce(1, (a, b) -> a * b); // 1*1*2*3*4*5 = 120

4. 수집 (결과 모으기): collect

가장 자주 사용되는 최종 연산 중 하나로, 스트림의 결과를 List, Set, Map 등의 컬렉션 구조나 특정 문자열로 담아 반환해줍니다. Collectors 클래스의 정적 메서드를 인자로 사용합니다.

List<String> items = Arrays.asList("Apple", "Banana", "Cherry");

// 1. List 타입으로 수집
List<String> upperItems = items.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());

// 2. 단일 문자열로 조인핑(Joining)
String resultText = items.stream()
.collect(Collectors.joining(", "));
// "Apple, Banana, Cherry"

최종 연산의 특성을 이해하고 적절한 메서드를 선택하여 사용하는 것이 자바 데이터 파이프라인 프로그래밍의 핵심입니다.

Advertisement