정리/Java
Java - Stream 최종 연산자(reduce)
난파선
2017. 3. 9. 12:00
reduce - 스트림의 요소를 하나씩 줄여가며 누적연산 수행
함수 인터페이스
- Optional<T> reduce(BinaryOperator<T> accumulator)
- T reduce(T identity, BinaryOperator<T> accumulator)
- U reduce(U identity, BiFunction<U,T,U> accumulator, BinaryOperator<U> combiner)
매개변수
- identity - 초기값
- accumulator - 이전 연산결과와 스트림의 요소에 수행할 연산
- combiner - 병렬처리된 결과를 합치는데 사용할 연산(병렬 스트림)
// OptionalInt reduce(IntBinaryOperator accumulator)// 연산된 결과값과 다음 값을 계속 비교한다.
OptionalInt max = intStream.reduce((a,b) -> a > b ? a : b); // max()
OptionalInt min = intStream.reduce((a,b) -> a < b ? a : b); // min()
// int reduce(int identity, IntBinaryOperator op)
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()
int count = intStream.reduce(0, (a,b) -> a + 1); // count()
int sum = intStream.reduce(0, (a,b) -> a + b); // sum()/*
int a = identity;
for(int b : stream)
a = a + b; // sum()
*/