SeouliteLab

[Java/자바] Stream.reduce() 메서드 사용 방법과 예제 본문

프로그래밍

[Java/자바] Stream.reduce() 메서드 사용 방법과 예제

Seoulite Lab 2024. 3. 9. 00:51

Stream.reduce() 메서드란?

Java 스트림(Stream) API에는 요소들을 처리하고 그 결과를 결합하는 데 사용되는 다양한 메서드가 있습니다. Stream.reduce() 메서드는 스트림의 요소들을 하나의 값으로 축소(reduce)하는 데 사용됩니다. 이 메서드는 초기값(initial value)과 BinaryOperator를 인수로 받아서 요소들을 순차적으로 결합하여 최종 결과를 생성합니다.

Stream.reduce() 메서드 사용 방법

Stream.reduce() 메서드는 다음과 같은 형식을 갖습니다:

Optional<T> reduce(BinaryOperator<T> accumulator)
T reduce(T identity, BinaryOperator<T> accumulator)
 U reduce(U identity,
            BiFunction<U, ? super T, U> accumulator,
            BinaryOperator<U> combiner)
  • accumulator: 스트림의 요소들을 결합하는 함수.
  • identity: 초기값. 스트림이 비어있을 때 반환되는 기본값입니다.
  • combiner: 병렬 처리 시 사용되는 함수. 스트림을 병렬로 처리할 때만 필요합니다.

Stream.reduce() 메서드 예제

다음은 Stream.reduce() 메서드를 사용한 예제 코드입니다.


import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class StreamReduceExample {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);

        // 스트림의 모든 요소를 합산
        Optional sum = numbers.stream().reduce((x, y) -> x + y);
        if (sum.isPresent()) {
            System.out.println("Sum of numbers: " + sum.get());
        }

        // 초기값 10과 함께 스트림의 모든 요소를 합산
        int initialValue = 10;
        int sumWithInitialValue = numbers.stream().reduce(initialValue, (x, y) -> x + y);
        System.out.println("Sum of numbers with initial value: " + sumWithInitialValue);

        // 병렬 처리를 위한 combiner 사용
        int sumParallel = numbers.parallelStream().reduce(0, Integer::sum, Integer::sum);
        System.out.println("Sum of numbers in parallel: " + sumParallel);
    }
}