java_basic
Lambda 기초5 최종연산 reduce
✨✨✨✨✨✨✨
2022. 2. 16. 12:19
반응형
스트림의 최종연산
가. reduce()
- Stream의 데이터를 더하거나 빼는 등 사칙연산을 사용하여 하나의 값으로 출력한다.
예제 : 1~10까지의 값을 모두 더하는 방법이다.
IntStream intStream = IntStream.rangeClosed(1, 10);
int num = intStream.reduce((x, y)-> x+y)
.orElse(0);
연산을 하기에 초기값 설정을 해준다. 연산을 하기에 초기값 설정 방법은 2가지가 있다.
첫번째 : orElse
IntStream intStream2 = IntStream.rangeClosed(1, 10);
int num = intStream.reduce((x, y)-> x+y)
.orElse(0);
System.out.println(num); //55
두번째 identity로 reduce에 직접 설정
IntStream intStream2 = IntStream.rangeClosed(1, 10);
int num2 = intStream2.reduce(0, (x, y)-> x+y);
System.out.println(num2); //55
위 결과는 같지만 차이점이 있다.
IntStream intStream = IntStream.rangeClosed(1, 3);
int num = intStream.reduce((x, y)-> (x+10) +(y+10))
.orElse(0);
System.out.println(num); // 46
(1+10) + (2+10) ==> 23 // 1, 2 (23+10) + (3+10) ==> 46 // sum, 3
reduce에 identity 초기값을 직접 설정해주면 해당값 부터 시작하기에 차이가 결과의 차이가 생긴다.
IntStream intStream2 = IntStream.rangeClosed(1, 3);
int num2 = intStream2.reduce(0,(x, y)-> (x+10) +(y+10));
System.out.println(num2); // 66
(0+10) + (1+10) ==> 21 // 0, 1 (21+10) + (2+10) ==> 43 // sum, 2 (43+10) + (3+10) ==> 66 // sum, 3
출처 : https://www.youtube.com/watch?v=SDjFCi7SMwA
반응형