본문 바로가기

JAVA

스트림9 최종연산 reduce()

최종연산 reduce() 최종연산중에서 가장 중요

스트림의 요소를 하나씩 줄여가며 누적연산 수행

 

Optional<T> reduce(BinaryOperator<T> accumulator)

T reduce(T identity , BinaryOperator<T> accumulator)

U reduce(T identity , BiFunction<U,T,U> accumulator),BinaryOperator<U> Combiner)

 

identity = 초기값,

accumulator = 이전 연산결과와 스트림의 요소에 수행할 연산

combiner = 병렬처리된 결과를 합치는데 사용할 연산(병렬스트림)

 

ex) int reduce(int identity , IntBinaryOperator op)

int Count = intStream.reduce(0,(a,b -> a+1)) //count 

이때

0 = identity = 초기값,

(a,b -> a+1) = accumulator 누적 연산

여기서 a는 초기값 0을 받게되고 b는 스트림의 각 요소의 값이다.

연산된 값은 계속 a초기값에 누적되게 된다.

최종적으로 a가 반환된다.

for(int b : stream){

 a = a+b; //sum()

}

 

int sum = intStream.reduce(0,(a,b -> a+b))

int max = intStream.reduce(Integer.min-value , (a,b) -> a > b ? a : b); //max값 뽑기

int min = intStream.reduce(Integer.max-value , (a,b) -> a < b ? a : b); //min값 뽑기