Java
스트림(Stream) - reduce( )
asdft
2024. 2. 27. 15:08
reduce(Identity, Accumulator -> Combiner)
- Identity – an element that is the initial value of the reduction operation and the default result if the stream is empty
- Accumulator – a function that takes two parameters: a partial result of the reduction operation and the next element of the stream
- Combiner – a function used to combine the partial result of the reduction operation when the reduction is parallelized or when there’s a mismatch between the types of the accumulator arguments and the types of the accumulator implementation
reduce(초기값, 인자 -> 함수 ) 연산
- 정의된 연산이 아닌 프로그래머가 직접 구현한 연산을 적용한다.
- 최종 연산으로 스트림의 요소를 소모하며 연산을 수행한다.
// 배열의 모든 요소의 합을 구하는 reduce( ) 연산 구현
Arrays.stream(arr).reduce(0, (a,b) -> a+b);
예시1)
Identity
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers
.stream()
.reduce(0, (subtotal, element) -> subtotal + element);
assertThat(result).isEqualTo(21);
이 경우, Integer 값인 0이 Identity이다. Integer값의 스트림이 비어있을때, 초기값인 identity를 저장한다.
Accumulator & Combiner
subtotal, element -> subtotal + element
int result = numbers.stream().reduce(0, Integer::sum);
assertThat(result).isEqualTo(21);
reduce( )연산을 다른 타입의 element에도 사용할 수 있다.
[참고]
https://www.baeldung.com/java-stream-reduce