본문 바로가기

명사 美 비격식 (무리 중에서) 아주 뛰어난[눈에 띄는] 사람[것]

JAVA

java.util.function패키지: BiConsumer<T, U> BiPredicate<T, U> BiFunction<T, U, R>

 

매개변수가 두개인 함수형 인터페이스는 이름앞에 Bi란 접두사가 붙는다.            

이 외 두개 이상의 매개변수를 갖는 함수형인터페이스가 필요하다면 직접 만들어 써야한다.

 

 

BiConsumer<T, U>
`accept(T t, U u)` 메서드를 호출해 두 개의 입력값을 받고 소비

import java.util.function.BiConsumer;

public class Main {
    public static void main(String[] args) {
        // BiConsumer를 이용하여 두 개의 정수를 더하여 출력하는 예시
        BiConsumer<Integer, Integer> adder = (a, b) -> System.out.println("Sum: " + (a + b));

        // BiConsumer에 두 개의 정수를 전달하여 더한 결과를 출력
        adder.accept(5, 3);
    }
}


[출력결과]
Sum: 8

 

 

 

 

BiPredicate<T, U>
`test(T t, U u)` 메서드를 호출하여 두 개의 입력값을 받아들이고 주어진 조건을 판별하여 boolean 값을 반환

import java.util.function.BiPredicate;

public class Main {
    public static void main(String[] args) {
        // BiPredicate를 이용하여 두 개의 정수가 같은지 확인하는 예시
        BiPredicate<Integer, Integer> isEqual = (a, b) -> a.equals(b);

        // BiPredicate에 두 개의 정수를 전달하여 같은지 여부를 확인
        System.out.println("Are 5 and 5 equal? " + isEqual.test(5, 5));
        System.out.println("Are 5 and 3 equal? " + isEqual.test(5, 3));

}


[출력결과]
Are 5 and 5 equal? true
Are 5 and 3 equal? false

 

 

 

BiFunction<T, U, R>
`apply(T t, U u)` 메서드를 호출하여 두 개의 입력값을 받아들이고 결과값을 반환

import java.util.function.BiFunction;

public class Main {
    public static void main(String[] args) {
        // BiFunction을 이용하여 두 개의 정수를 더하고 결과를 문자열로 변환하는 예시
        BiFunction<Integer, Integer, String> adderToString = (a, b) -> "Sum: " + (a + b);

        // BiFunction에 두 개의 정수를 전달하여 더한 결과를 문자열로 변환하여 반환
        System.out.println(adderToString.apply(5, 3));
    }



[출력결과]
Sum: 8