1. reduce() 연산
- Stream에서 정의된 연산이 아닌 프로그래머가 직접 구현한 연산을 적용
<java />
T reduce(T identify, BinaryOperator<T> accumulator)
//reduce 메소드의 두 번째 파라미터로 직접 구현 가능
//직접 구현하기 어렵다면 BinaryOperator를 상속받자
- 최종 연산으로 스트림의 요소를 소모하며 연산을 수행
- 배열의 모든 요소의 합을 구하는 reduce() 연산 구현 예
<java />
Arrays.stream(arr).reduce(0, (a,b)->a+b));
//초기값, 매개 변수, 매개 변수로 수행할 식
- reduce() 메서드의 두 번째 요소로 전달되는 람다식에 따라 다양한 기능을 수행 할 수 있음
- 람다식을 직접 구현하거나 람다식이 긴 경우 BinaryOperator를 구현한 클래스를 사용 함
2. BinaryOperator를 구현하여 배열에 여러 문자열이 있을 때 길이가 가장 긴 문자열 찾기 예
<java />
package ch07;
import java.util.Arrays;
import java.util.function.BinaryOperator;
public class ReduceTest {
class CompareString implements BinaryOperator<String>{ //BinaryOperator를 구현한 클래스를 reduce() 괄호 안에 넣으면 된다
@Override
public String apply(String s1, String s2) {
if (s1.getBytes().length>=s2.getBytes().length) return s1;
else return s2;
}
}
public static void main(String[] args) {
String greetings[ ] = {"안녕","hello","니 하오"};
//람다식으로 직접 쓰기
System.out.println(Arrays.stream(greetings).reduce("",(s1,s2)->
{if (s1.getBytes().length>=s2.getBytes().length) return s1;
else return s2;}
));
//reduce 사용하기
String str = Arrays.stream(greetings).reduce(new CompareString()).get();
System.out.println(str);
}
}
'JAVA' 카테고리의 다른 글
Static이란? (0) | 2023.02.14 |
---|---|
Stream 활용 예제 (0) | 2022.06.22 |
Stream (0) | 2022.06.21 |
6-4.스트림(Stream) (0) | 2022.02.27 |
6-3.객체지향 프로그래밍 vs 람다식 차이 (0) | 2022.02.26 |