Java BiranryOperator 와 Reduce에 대해서 알아보자.
포스트
취소

Java BiranryOperator 와 Reduce에 대해서 알아보자.

JAVA BinaryOperator 란?

BiranryOperator 는 같은 타입의 파라미터 2개를 받아 결과 값을 리턴하는 functional interface 이다.

http://res.cloudinary.com/dygjhmhpo/image/upload/v1692518044/F05NLPFC802.png

java BinaryOperator 명세

BiranryOperator vs BiFunction 비교

BiranryOperatorBiFunction은 두개의 값을 받아서 하나의 값을 반환 하기 떄문에 언뜻 차이가 없어 보이지만,

BiranryOperator vs BiFunction 비교

인터페이스의 인수 유형과 반환 유형에 차이가 있다.

두 문자열을 연결하고 연결한 결과를 반환 하는 경우에는 아래의 예시처럼 인수와 반환 유형이 동일하기 때문에 BiranryOperator, BiFunction 두 가지 모두 선택 가능 하지만 반환 유형이 모두 동일하기 떄문에 BiranryOperator를 선택 하는 것이 좋다. http://res.cloudinary.com/dygjhmhpo/image/upload/v1692515983/F05NP5V1TB6.png

하지만 아래의 케이스 처럼 두개의 정수를 더하고 문자열을 반환 하는 경우에는 타입이 다르기 떄문에 BiFunction만 선택할 수 있다.

http://res.cloudinary.com/dygjhmhpo/image/upload/v1692516121/F05N66GUW23.png

Reduce

스트림은 reduce 라는 메소드를 통해서 여러가지 결과를 만들어 낼수 있는데, 여기서 BinaryOperator가 사용되고 있다. 각 메소드를 살펴 보자.

  • Optional<T> reduce(BinaryOperator<T> accumulator);
  • T reduce(T identity, BinaryOperator<T> accumulator);
  • <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);

1. 누적기능

accumulator 를 주입 받아서 누적된 결과를 반환 가능하다.

1
	Optional<T> reduce(BinaryOperator<T> accumulator);

위 코드는 아래의 코드와 결과가 같다.

1
2
3
4
5
6
 U result = identity;  
 for (T element : this stream)  
     result = accumulator.apply(result, element)  
 return result;

2. 초기값이 있는 누적

1
	T reduce(T identity, BinaryOperator<T> accumulator);

기본적인 누적 기능과 동일하지만 T identity 를 통해서 초기 값을 전달 받을 수 있다. list에 값이 없더라고 indentity 의 값이 반환 된다.

3. 병렬 처리를 통한 누적

1
 <U> U reduce(U identity,  BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);

마지막으로 3개의 인자를 전달 받는 reduce 함수이다.

아래의 코드 처럼 함수를 실행 하였을때

1
2
3
4
5
6
7
8
9
10
11
12
Integer result = ret  
        .stream()  
        .reduce(10,  
                (a, b) -> {  
                    System.out.println("accumulator");  
                    return a + b;  
                },  
                (a, b) -> {  
                    System.out.println("combiner");  
                    return a + b;  
                }  
        );

다음과 같잉 combiner 는 실행 되지 않는것을 확인 할 수 있는데.

http://res.cloudinary.com/dygjhmhpo/image/upload/v1692517486/F05NP6R4V52.png

combiner 는 병렬(parallel) 스트림에서 나눠 계산한 결과를 하나로 합치는 동작을 하기 때문에 .parallelStream() 을 호출해주어야 동작한다.

1
2
3
4
5
6
7
8
9
10
11
12
Integer result = ret  
        .parallelStream()  
        .reduce(10,  
                (a, b) -> {  
                    System.out.println("accumulator");  
                    return a + b;  
                },  
                (a, b) -> {  
                    System.out.println("combiner");  
                    return a + b;  
                }  
        );

http://res.cloudinary.com/dygjhmhpo/image/upload/v1692517712/F05N67EUVE3.png

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.