프로그래머가 직접 구현한 연산을 적용
T reduce(T identify, BinaryOperator<T> accumulator)
최종 연산으로 스트림의 요소를 소모하며 연산수행
배열의 모든 요소의 합을 구하는 reduce() 구현 예
Arrays.stream(arr).reduce(0, (a,b)->a+b));
reduce()함수의 두번째 요소로 전달되는 람다식에 따라 다양한 기능을 수행 할 수 있다
람다식을 직접 구현하거나 람다식이 긴 경우 BinaryOperator를 구현한 클래스를 사용한다
Reduce 를 사용해서 가장큰 크기의 문자열을 출력하는 예
String greetings[] = {"만나서 반가워요","Hello There~~", "Hello", "Good morning", "Nice to meet you Bie"};
System.out.println(Arrays.stream(greetings).reduce("", (s1, s2)->
{
if (s1.getBytes().length >= s2.getBytes().length) return s1;
else return s2;
}
));
BinaryOperator 인터페이스를 활용한 예
class CompareString implements BinaryOperator<String>
{
@Override
public String apply(String s1, String s2) {
if (s1.getBytes().length >= s2.getBytes().length) return s1;
else return s2;
}
}
String greetings[] = {"만나서 반가워요","Hello There~~", "Hello", "Good morning", "Nice to meet you Bie"};
System.out.println(Arrays.stream(greetings).reduce(new CompareString()).get());