Java Stream reduce 함수에 대한 설명입니다.
바로 소스로 들어가보자!
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class StreamReduce {
public static void main(String[] args) {
//Optional<T> reduce(BinaryOperator<T> accumulator);
OptionalInt reduced1 = IntStream.range(1, 5) // [1, 2, 3, 4]
.reduce((a, b) -> {
System.out.println("a = " + a);
System.out.println("b = " + b);
return Integer.sum(a, b);
});
System.out.println(reduced1.getAsInt());
//T reduce(T identity, BinaryOperator<T> accumulator);
int reduced2 = IntStream.range(1, 5) // [1, 2, 3, 4]
.reduce(10, (a, b) -> {
System.out.println("a = " + a);
System.out.println("b = " + b);
return Integer.sum(a, b);
});
System.out.println(reduced2);
}
}
긴말 필요 없이 결과도 바로 확인해보자!
a = 1
b = 2
a = 3
b = 3
a = 6
b = 4
10
a = 10
b = 1
a = 11
b = 2
a = 13
b = 3
a = 16
b = 4
20
Stream 생성 했던 IntStream 의 range 함수는 Javadoc 으로 확인해본다.
IntStream (Java Platform SE 8 ) (oracle.com)
※ 첫번째 파라미터는 포함, 두번째 파라미터는 불포함
- 항상 헷갈리는 부분이니까 꼼꼼히 읽어보자!!
static IntStream range(int startInclusive, int endExclusive)
Returns a sequential ordered IntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1.
API Note:
An equivalent sequence of increasing values can be produced sequentially using a for loop as follows:
for (int i = startInclusive; i < endExclusive ; i++) { ... }
Parameters:
startInclusive - the (inclusive) initial value
endExclusive - the exclusive upper bound
Returns:
a sequential IntStream for the range of int elements
자, 이제 본격적으로 Stream reduce 에 대한 설명 들어보고 가실께여~
1. 먼저 파라미터가 1개인 reduce 함수
//Optional<T> reduce(BinaryOperator<T> accumulator);
OptionalInt reduced1 = IntStream.range(1, 5) // [1, 2, 3, 4]
.reduce((a, b) -> {
System.out.println("a = " + a);
System.out.println("b = " + b);
return Integer.sum(a, b);
});
System.out.println(reduced1.getAsInt());
첫번째 실행
- a : Stream 의 첫번째 값 = 1
- b : Stream 의 두번째 값 = 2
- a + b = 3 을 반환(return) 한다.
두번째 실행
- a : 첫번째 실행한 결과 값 = 3
- b : Stream 의 다음(세번째) 값 = 3
- a + b = 6 을 반환(return) 한다.
세번째 실행
- a : 두번째 실행한 결과 값 = 6
- b : Stream 의 다음(네번째) 값 = 4
- a + b = 10 을 반환(return) 한다.
최종 실행 결과 값으로 10을 반환한다.
2. 먼저 파라미터가 2개인 reduce 함수
- reduce 함수의 첫번째 파라미터는 초기 값을 의미한다.
//T reduce(T identity, BinaryOperator<T> accumulator);
int reduced2 = IntStream.range(1, 5) // [1, 2, 3, 4]
.reduce(10, (a, b) -> {
System.out.println("a = " + a);
System.out.println("b = " + b);
return Integer.sum(a, b);
});
System.out.println(reduced2);
첫번째 실행
- a : 초기 값 = 10
- b : Stream 의 첫번째 값 = 1
- a + b = 11 을 반환(return) 한다.
두번째 실행
- a : 첫번째 실행한 결과 값 = 11
- b : Stream 의 다음(두번째) 값 = 2
- a + b = 13 을 반환(return) 한다.
세번째 실행
- a : 두번째 실행한 결과 값 = 13
- b : Stream 의 다음(세번째) 값 = 3
- a + b = 16 을 반환(return) 한다.
네번째 실행
- a : 세번째 실행한 결과 값 = 16
- b : Stream 의 다음(네번째) 값 = 4
- a + b = 20 을 반환(return) 한다.
최종 실행 결과 값으로 20을 반환한다.
위에서 살펴본 Stream reduce 두 함수의 차이는 초기 값이 있냐 없냐의 차이이다.
그리고 Stream reduce 함수에서 가장 중요하게 봐야할 부분은 accumulator 의 동작 방식이다.
첫번째, 두번째 인자에 값이 어떻게 전달되어 최종 결과값을 반환하는지에 대한 이해만 있다면 어렵지 않을 것이다.
Stream reduce 에 대한 Javadoc 페이지도 같이 확인하면 좋을 것 같아 링크를 건다.
Stream (Java Platform SE 8 ) (oracle.com)
'프로그래밍 > Java' 카테고리의 다른 글
[java] 엑셀 읽기 에러 Exception in thread "main" java.lang.NoSuchMethodError: org.apache.logging.log4j.Logger.atDebug()Lorg/apache/logging/log4j/LogBuilder; (0) | 2023.06.15 |
---|---|
Java Stream 설명 (0) | 2023.05.26 |
java file.encoding (0) | 2022.07.12 |
[JAVA] java.lang.UnsatisfiedLinkError: no net in java.library.path (1) | 2021.06.25 |
Too many open files (2) | 2021.06.14 |