최종연산 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값 뽑기
'JAVA' 카테고리의 다른 글
스트림11 스트림의 collector로 reducing 그룹별 리듀싱 (0) | 2023.03.17 |
---|---|
스트림10 최종연산 collect 와 colltors (0) | 2023.03.16 |
스트림8 최종연산 forEach() (0) | 2023.03.16 |
Optional<T> (0) | 2023.03.16 |
스트림7 flatMap() 스트림의 스트림을 스트림으로 변환 (0) | 2023.03.16 |