본문 바로가기

개발

[Java] UnaryOperator, BinaryOperator 함수형 인터페이스

 


 

1. UnaryOperator

UnaryOperator는 Function의 자손이다.

그러나 Parameter Type과 Return Type이 같다.

 

    @Test
    @DisplayName("UnaryOperator를 활용한 replaceAll()")
    void UnaryOperatorTest() {
        UnaryOperator<Integer> makeTwice = n -> n * 2;

        List<Integer> originList = Arrays.asList(1, 2, 3);
        originList.replaceAll(makeTwice);

        List<Integer> resultList = Arrays.asList(2, 4, 6);
        assertThat(originList).isEqualTo(resultList);
    }

 

2. BinaryOperator

BinaryOperator는 BiFunction의 자손이다.

그러나 Parameter Type과 Return Type이 같다.

 

    @Test
    @DisplayName("BinaryOperator를 활용한 reduce()")
    void BinaryOperatorTest() {
        BinaryOperator<Integer> makeCalc = (x, y) -> (x * 2) + y;

        List<Integer> originList = Arrays.asList(1, 2, 3);
        assertThat(originList.stream().reduce(makeCalc).get()).isEqualTo(11);
    }

 


 

 

 

https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html

 

java.util.function (Java Platform SE 8 )

Interface Summary  Interface Description BiConsumer Represents an operation that accepts two input arguments and returns no result. BiFunction Represents a function that accepts two arguments and produces a result. BinaryOperator Represents an operation u

docs.oracle.com