[Reactive] 04. 리액티브 프로그래밍을 위한 사전 지식

Jimin Lim·2024년 3월 3일
0

Spring

목록 보기
11/18
post-thumbnail

4.1 함수형 인터페이스

함수형 프로그래밍에서는 함수를 일급 시민으로 취급한다. Java 8 에서도 이러한 기능이 추가되었으며, 그걸 함수형 인터페이스 라고 한다.

  • 일급 시민: 함수를 값으로 취급, 함수 자체를 파라미터로 전달할 수 있음
  • 함수형 인터페이스: 단 하나의 추상 메서드만 정의

4.2 람다 표현식

  • 람다 표현식: 인터페이스 자체를 익명 구현 객체로 전달하던 방식을 좀 더 함수형 프로그래밍 방식에 맞게 표현할 수 있도록 지원
//익명 구현 객체로 전달 
Collections.sort(cryptoCurrencies, new Comparator<CryptoCurrency>() {
            @Override
            public int compare(CryptoCurrency cc1, CryptoCurrency cc2) {
                return cc1.getUnit().name().compareTo(cc2.getUnit().name());
            }
        });

//람다
Collections.sort(cryptoCurrencies, (cc1, cc2) -> cc1.getUnit().name().compareTo(cc2.getUnit().name()));

여기서 람다 표현식으로 작성해 파라미터로 전달한다는 것은 메서드 자체를 파라미터로 전달하는 것이 아니라, 함수형 인터페이스를 구현한 클래스의 인스턴스를 람다 표현식으로 작성해서 전달하는 것이다.

4.3 메서드 레퍼런스

위와 같이 좀 더 축약할 수 있다. 이처럼 메서드 레퍼런스로 표현할 수 있는 유형은 네 가지가 있다.

ClassName::static method

        cryptoCurrencies.stream()
                .map(cc -> cc.getName())
//                .map(name -> StringUtils.upperCase(name))
                .map(StringUtils::upperCase)
                .forEach(name -> System.out.println(name));
  • 컴파일러가 파라미터 형식 추론해서 파라미터 생략 가능

ClassName::instance method

        cryptoCurrencies.stream()
                .map(cc -> cc.getName())
//                .map(name -> name.toUpperCase())
                .map(String::toUpperCase)
                .forEach(name -> System.out.println(name));
  • String 클래스의 인스턴스 메서드 사용

object::instance method

        PaymentCalculator calculator = new PaymentCalculator();
        cryptoCurrencies.stream()
                .filter(cc -> cc.getUnit() == CurrencyUnit.BTC)
                .map(cc -> new ImmutablePair(cc.getPrice(), amount))
//                .map(pair -> calculator.getTotalPayment(pair))
                .map(calculator::getTotalPayment)
                .forEach(System.out::println);

className::new

        Optional<PaymentCalculator> optional =
                cryptoCurrencies.stream()
                                .filter(cc -> cc.getUnit() == CurrencyUnit.BTC)
                                .map(cc -> new ImmutablePair(cc.getPrice(), amount))
//                                            .map(pair -> new PaymentCalculator(pair))
                                .map(PaymentCalculator::new)
                                .findFirst();

4.4 함수 디스크립터

  • 함수 디스크립터: 이 함수형 인터페이스가 어떤 파라미터, 리턴 값을 가지는지 설명

이 중 몇 가지 예시를 알아보자 >_<

Predicate

    public static void main(String[] args) {
        List<CryptoCurrency> cryptoCurrencies = SampleData.cryptoCurrencies;
        List<CryptoCurrency> result = filter(cryptoCurrencies, cc -> cc.getPrice() > 500_000);

        for (CryptoCurrency cc : result) {
            System.out.println(cc.getName());
        }
    }

    private static List<CryptoCurrency> filter(List<CryptoCurrency> cryptoCurrencies,
                                               Predicate<CryptoCurrency> p){
        List<CryptoCurrency> result = new ArrayList<>();
        for (CryptoCurrency cc : cryptoCurrencies) {
            if (p.test(cc)) {
                result.add(cc);
            }
        }
        return result;
    }
  • 람다 표현식으로 전달한 파라미터를 Predicate 로 전달받는것을 확인할 수 있다.

Supplier

    public static void main(String[] args) {
        String mnemonic = createMnemonic();
        System.out.println(mnemonic);
    }


    private static String createMnemonic() {
        return Stream
                .generate(() -> getMnemonic())
                .limit(12)
                .collect(Collectors.joining(" "));
    }

    private static String getMnemonic() {
        List<String> mnemonic = Arrays.asList(
                    "alpha", "bravo", "charlie",
                    "delta", "echo", "foxtrot",
                    "golf", "hotel", "india",
                    "juliet", "kilo", "lima",
                    "mike", "november", "oscar",
                    "papa", "quebec", "romeo",
                    "sierra", "tango", "uniform",
                    "victor", "whiskey", "xray",
                    "yankee", "zulu"
                );
        Collections.shuffle(mnemonic);
        return mnemonic.get(0);
    }
profile
💻 ☕️ 🏝 🍑 🍹 🏊‍♀️

0개의 댓글