코드지우개

람다식 ③ 본문

java

람다식 ③

코드지우개 2023. 6. 5. 11:33
반응형
andThen()과 compose() 디폴트 메소드

디폴트 및 정적 메소드는 추상 메소드가 아니기 때문에 함수적 인터페이스에 선언되어도 여전히 함수적 인터페이스의 성질을 잃지 않는다.
여기서 함수적 인터페이스 성질이란 하나의 추상 메소드를 가지고 있고, 람다식으로 익명 수현 객체를 생성할 수 있는 것을 말한다.

 

Consumer, Function, Operator 종류의 함수적 인터페이스는 andThen()과 compose() 디폴트 메소드를 가지고 있다.

  • 함수적 인터페이스가 가지고 있는 디폴트 메소드이다.
  • 두 개의 함수적 인터페이스를 순차적으로 연결해서 실행한다.
  • 첫 번째 리턴 값을 두 번째 매 개값으로 제공해서 최종 결과값 리턴한다.
  • andThen()과 compose()의 차이점은 어떤 함수적 인터페이스부터 처리하느냐이다.

andThen() : 위에 그림을 보면 인터페이스 A와 B를 andThen()으로 연결을 한 후 인터페이스 AB.method()를 호출하게 되면 먼저 인터페이스 A에 람다식이 먼저 실행이 되고 그 결과값을 받아서 인터페이스 B에 매 개값으로 제공을 해준다 그리고 인터페이스 B가 결과값을 내게 되면 최종 결과 값으로 리턴해준다.

comPose() : 위에 그림을 보면 인터페이스 A와 B를 compose()으로 연결을 한 후 인터페이스 AB.method()를 호출하게 되면 먼저 인터페이스 B에 람다식이 먼저 실행이 되고 그 결과값을 받아서 인터페이스 A에 매 개값으로 제공을 해준다 그리고 인터페이스 A가 결과값을 내게 되면 최종 결과 값으로 리턴해준다.

 

andThen()과 compose() 디폴트 메소드를 제공하는 함수적 인터페이스

종류
함수적 인터페이스
andThen()
compose()
Consumer
Consumer<T>
O

BiConsumer<T,U>
O

DoubleConsumer
O

IntConsumer
O

LongConsumer
O

Function
Function<T,R>
O
O
BiFunction<T,U,R>
O

Operator
BinaryOperator<T>
O

DoubleUnaryOperator
O
O
IntUnaryOperator
O
O
LongUnaryOperator
O
O

 
Consumer의 순차적 연결

Consumer 종류의 함수적 인터페이스는 처리 결과를 리턴하지 않기 때문에 andThen() 디폴트 메소드는 함수적 인터페이스의 호출 순서만 정한다.

 

위에 그림을 보면 Consumer 함수적 인터페이스가 2개가 만들어져 있다.

1. consumerA는 Member 객체를 받아 Member 객체에 이름(getName)을 출력

2. consumerB는 Member 객체를 받아 Member 객체에 아이디(getId)를 출력

3. consumerAB를 선언을 하고 consumerA와 consumerB를 andThen()으로 연결

4. accept() 메소드를 호출 (매 개값으로 Member 객체를 제공)

실행 결과를 보면 처음에 consumerA가 먼저 실행이 돼서 이름이 출력이 되고 그 후 consumerB가 실행이 돼서 아이디가 출력이 된다.

 

Example
public class Member{
    private String name;
    private String id;
    private Address address;

    public Member(String name, String id, Address address){
        this.name = name;
        this.id = id;
        this.address = address
    }

    public String getName(){
        return name;
    }    
    public String getId(){
        return id;
    }
    public Address getAddress(){
        return address;
    }
}
 
public class Address{
    private String country;
    private String city;

    public Address(String country, String city){
        this.country = country;
        this.city = city;
    }
    
    public String getCountry{
        return country;
    }
    public String getCity{
        return city;
    }

}
 
public class ConsumerAndThenExample{

    public static void main(String[] args){
        Consumer<Member> consumerA = (m) -> {
	        System.out.println("consumerA : " + m.getName());
        };
        Consumer<Member> consumerB = (m) -> {
        	System.out.println("consumerB : " + m.getId());
        };
        Consumer<Member> consumerAB = consumerA.andThen(consumerB); //순서를 바꾸고싶으면 consumerB.andThen(consumerA);
        consumerAB.accept( new Member("홍길동", "hong") );
        //출력 
        consumerA : 홍길동
        consumerB : hong
    }
}
 
 

Function 순차적 연결

Function과 Operator 종류의 함수적 인터페이스는 먼저 실행한 함수적 인터페이스의 결과를 다음 함수적 인터페이스의 매 개값으로 넘겨주고, 최종 처리결과를 리턴한다.

1. Function 함수에 Member 객체를 제공해 주면 Address 객체를 리턴해준다.
2. 다음 함수적 인터페이스인 Function에 첫 번째 Function 함수에 리턴 값인 Address를 제공받아 최종적으로 String을 리턴한다.

여기서 Address 객체는 결국 Member 객체에서 String으로 리턴하기 위해서 중간에 생성되었다가 사라지는 값이다.

그래서 결국 Member 객체를 제공해 주고 String을 리턴 받는 결과하고 같다.

 

 

Example
public class FunctionAndThenComposeExample{

    public static void main(String[] args){
     
        Function<Member, Address> functionA;
        Function<Address, String> functionB;
        Function<Member, String> functionAB;
        String city;

        functionA = (m) -> m.getAddress(); //Member 매개값
        functionB = (a) -> a.getCity();   //Address 매개값

        functionAB = functionA.andThen(functionB); //functionA 먼저 실행 후 functionB 실행 (functionA 결과값인 Address가 function B 매가값으로 제공된다.)
        city = functionAB.apply(
            new Member("홍길동", "hong", new Address("한국", "서울")) 
        );
        System.out.println( "거주 도시 : " + city ); // 출력: 거주 도시 : 서울

        functionAB = functionB.compose(functionA);
        city = functionAB.apply(
            new Member("홍길동", "hong", new Address("한국", "서울")) 
        );
        System.out.println( "거주 도시 : " + city ); // 출력: 거주 도시 : 서울


    }  
}
 

 

반응형

'java' 카테고리의 다른 글

람다식 ⑤  (0) 2023.09.05
람다식 ④  (0) 2023.06.05
람다식 ②  (0) 2023.06.05
람다식 ①  (0) 2023.04.13
인터페이스 ④  (0) 2023.04.13
Comments