Java 문법

java.util.function 패키지(지속 작성중..)

개발하는지호 2024. 1. 9. 17:05

람다식을 사용할 때 마다 함수형 인터페이스를 매번 정의하기 불편하다.

 

그래서 라이브러리로 제공하는 것들이 있다.

 

자바8에서 제공하는 주요 Functional 인터페이스는 java.util.function 패키지에 다음과 같이 있다.

 

  • Predicate
  • Supplier
  • Consumer
  • Function
  • UnaryOperator
  • BinaryOperator

이미지 출처 : https://javaplant.tistory.com/34

Predicate

boolean 을 리턴하며, <> 안에는 어떤 타입들에 의해 true , false가 나오는지 적는다. 

 

ex)

import java.util.function.Predicate;

class Main {
    public static void main(String[] args) {
        Predicate<Integer> predicate = (a) -> a > 10;
    }
}

 

 

Supplier

get() 메서드가 있어, 리턴값은 generic으로 선언된 타입을 리턴한다. 다른 인터페이스들과는 다르게 추가적인 메서드는 선언되어 있지 않다. *매개 변수가 없다.

 

import java.util.function.Supplier;

class Main {
    public static void main(String[] args) {
        Supplier<String> a = () -> "Happly New Year";

        System.out.println(a.get());
    }
}

 

https://javaplant.tistory.com/34