함수형 인터페이스

✒️ 2025-05-23 16:39 내용 수정


람다식을 사용할 때 참조하는 참조 변수의 타입

@FunctionalInterface
public interface MyFunctionalInterface {
    void execute(); // 유일한 추상 메서드

    default void log(String message) {
        System.out.println("Log: " + message);
    }

    static void print(String message) {
        System.out.println(message);
    }
}

java.util.function

이름 메서드 특징
Supplier T get() 매개변수 0, 반환값 O
Consumer void accept(T t) 매개변수 1, 반환값 X
Function<T,R> R apply(T t) 매개변수 1, 반환값 O
Predicate boolean test(T t) 매개변수 1, 반환값 항상 논리형
BiConsumer<T,U> void accept(T t, U u) 매개변수 2, 반환값 X
BiPredicate<T,U> boolean test(T t, U u) 매개변수 2, 반환값 논리형
BiFunction<T,U,R> R apply<T t, U u> 매개변수 2, 반환값 O
@FunctionalInterface // 함수형 인터페이스 명시!
public interface CompareNumber { // 함수형 인터페이스!
	int compareTo(int num01, int num02);
}

public CompareMain {

	public static void main(String[] args) {
	// 함수형 인터페이스의 타입으로 람다식!
		CompareNumber compare = (num01, num02) -> {return x > y ? x : y};
		System.out.println(compare.compareTo(num01, num02));
	}
}

람다식의 합성과 결합

// Function<T,R>의 R apply<T t> 사용
import java.util.function.Function;
public class Ex2_function2 {
	public static void main(String[] args) {
		// String을 16진수의 int로 변환
		Function<String, Integer> f = s -> Integer.parseInt(s, 16);
		// int를 2진수로 바꾸어 String으로 변환
		Function<Integer, String> g = i -> Integer.toBinaryString(i);

		Function<String, String> h = f.andThen(g); // FF -> 255 -> 11111111
		System.out.println(h.apply("FF"));
		Function<Integer, Integer> h2 = f.compose(g); // 2 -> 10 -> 16
		System.out.println(h2.apply(2));
		Function<String, String> f2 = x -> x;
		System.out.println(f2.apply("hello"));
	}
}
11111111
16
hello
import java.util.function.Predicate;
public class Ex2_function2 {
	public static void main(String[] args) {
		Predicate<Integer> p = i -> i < 100;
		Predicate<Integer> q = i -> i < 200;
		Predicate<Integer> r = i -> i % 2 == 100;

		Predicate<Integer> notP = p.negate(); // negate는 not이므로 i >= 100
		Predicate<Integer> all = notP.and(q.or(r)); // i>=100 &&(i<200||i%2==0)
		System.out.println(all.test(150));
	}
}
true

람다식의 메서드 참조

클래스이름::메서드이름
참조변수::메서드이름
import java.util.function.BiFunction;
import java.util.function.Function;

public class Ex3_function3 {
	public static void main(String[] args) {
		//Function<String, Integer> f = (String s) -> Integer.parseInt(s);
		Function<String, Integer> f = Integer::parseInt;

		//BiFunction<String, String, Boolean> f2 = (s1, s2) -> s1.equals(s2);
		BiFunction<String, String, Boolean> f2 = String::equals;

		// 정적 메서드의 참조
		IntBinaryOperator operator;
		//operator = (x,y) -> Math.max(x,y);
		operator = Math::max;
		System.out.println(operator.applyAsInt(10, 20));
	}
}
20