inblog logo
|
LifeLog, DevLog
    Java

    함수형 인터페이스

    KYJTHEYJ's avatar
    KYJTHEYJ
    Dec 22, 2025
    함수형 인터페이스
    Contents
    함수형 인터페이스핵심주요 인터페이스

    함수형 인터페이스

    함수형 인터페이스는 추상 메서드가 1개만 정의된 인터페이스들의 총칭

    핵심

    • 동작을 값처럼 다룰 수 있다

    • 람다 표현식의 타입 역할을 한다

    • 코드의 재사용성이 높다

    • 조합이 가능하다

    • 선언적 프로그래밍

      // 지시하는 명령형 (루프, 조건문, 변수에 할당 명령으로 조합)
      List<String> names = new ArrayList<>();
      for (Product p : products) {
          if (p.getPrice() > 10000) {
              String name = p.getName();
              names.add(name);
          }
      }
      
      // 무엇을 원하는지 선언하는 선언형 (원하는 결과만 표현하고 구현은 라이브러리가)
      List<String> names = products.stream()
          .filter(p -> p.getPrice() > 10000)  // 가격 1만원 초과인 것을
          .map(Product::getName)               // 이름으로 변환
          .collect(Collectors.toList());       // 리스트로 수집

    주요 인터페이스

    • Consumer<T> → 소비

      Consumer<Product> printer = p -> System.out.println(p.getName());
      products.forEach(printer);
      • 타입을 받아 출력, 저장, 수정하는 등의 소비만 수행함

    • Function<T, R> → 변환

      Function<Product, String> toName = Product::getName;
      List<String> names = products.stream().map(toName).toList();
      • 타입을 받아 가공하는 등의 변환을 수행함

    • Predicate<T> → 조건

      Predicate<Product> expensive = p -> p.getPrice() > 100000;
      List<Product> filtered = products.stream().filter(expensive).toList();
      • 타입을 받아 타입의 조건을 만듬 (필터링 등에 사용)

    • BiPredicate<T, U> - Predicate 의 조건의 입력이 2개인 것

      BiPredicate<Product, Integer> canOrder = (product, quantity) -> 
          product.getStock() >= quantity;
      
      BiPredicate<User, Product> canPurchase = (user, product) -> 
          user.getBalance() >= product.getPrice();
      
      // 사용
      if (canOrder.test(product, 5)) {
          System.out.println("주문 가능");
      }
      
      if (canPurchase.test(user, product)) {
          System.out.println("구매 가능");
      }
      
      // 조합
      BiPredicate<User, Product> canBuy = (user, product) -> 
          canPurchase.test(user, product) && 
          canOrder.test(product, 1);
    • Supplier<T> → 생성

      Supplier<Product> factory = () -> new Product("기본", 0, "", 0);
      Product product = Optional.ofNullable(find()).orElseGet(factory);
      • 타입을 받아 타입의 객체를 생성

    • Callable, Runnable → 둘다 비동기 처리 (Callable은 반환값이 있을 경우)

      @FunctionalInterface
      public interface Callable<V> {
          V call() throws Exception;
      }

    Share article
    Contents
    함수형 인터페이스핵심주요 인터페이스

    LifeLog, DevLog - https://github.com/KYJTHEYJ

    RSS·Powered by Inblog