BiFunction 인터페이스란 ?
BiFunction Interface는 함수형 인터페이스로 java 1.8부터 사용되며 두 개의 매개변수를 전달받아 결과값을 생성하는 함수를 나타냅니다.
BiFunction.java
@FunctionalInterfase
public interface BiFunction<T, U, R>{
R apply(T t, U u);
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNul(after);
return (T t, U u) -> after.apply(apply(t, u));
}
}
- 인터페이스 내부에 추상메서드 apply()와 디폴트 메서드인 andThen() 메서드가 존재
- BiFunction 인터페이스는 세 개의 제너릭 타입을 사용
- T : 첫 번째 매개변수 타입
- U : 두 번째 매개변수 타입
- R : 반환 타입
BiFunction 인터페이스의 apply()
apply() 메서드는 두 개의 매개변수를 전달받아 값을 반환하는 메서드입니다.
[apply() 예제]
- biFunction1 객체는 두 개의 Integer 타입의 매개변수를 전달받아 해당 매개변수를 '>=' 로 비교한 값을 리턴합니다. (boolean)
- biFunction2 객체는 두 개의 Integer 타입의 매개변수를 전달받아 해당 매개변수를 '<' 로 비교한 값을 리턴합니다. (boolean)
import java.util.function.BiFunction;
public class BifunctionEx {
public static void main(String[] args) {
BiFunction<Integer, Integer, Boolean> biFunction1 = (a, b) -> a >= b;
BiFunction<Integer, Integer, Boolean> biFunction2 = (a, b) -> a < b;
System.out.println("10 >= 2 : " + biFunction1.apply(10, 2));
System.out.println("1 >= 5 : " + biFunction1.apply(1, 5));
System.out.println("3 < 78 : " + biFunction2.apply(3, 78));
System.out.println("99 < 43 : " + biFunction2.apply(99, 43));
}
}
[실행 결과]
10 >= 2 : true
1 >= 5 : false
3 < 78 : true
99 < 43 : false
BiFunction 인터페이스의 andThen()
apply() 메서드 실행 후 결과에 다음 함수를 적용시킨 결과를 반환하는 메서드입니다.
매개변수 타입은 Function 타입을 전달합니다.
[andThen() 예제]
- 문장과 단어를 입력받은 뒤 단어가 문장에 포함되어있는지 확인하는 예제입니다.
- apply() 메서드 반환 결과를 가지고 andThen() 을 사용하여 문자열을 출력합니다.
import java.util.Scanner;
import java.util.function.BiFunction;
public class BifunctionEx {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputSentence = sc.nextLine();
String inputWord = sc.nextLine();
BiFunction<String, String, String> isContains
= (sentence, word) -> String.valueOf(sentence.contains(word));
isContains = isContains.andThen(result -> Boolean.valueOf(result) ? "해당 문자열이 포함되어있습니다." : "해당 문자열은 포함되어있지 않습니다.");
System.out.println("====================================");
System.out.println("문장 : " + inputSentence);
System.out.println("찾을 단어 : " + inputWord);
System.out.println("====================================");
System.out.println("결과 : " + isContains.apply(inputSentence, inputWord));
}
}
[실행 결과]
- 참고문헌
https://docs.oracle.com/javase/8/docs/api/java/util/function/BiFunction.html
BiFunction (Java Platform SE 8 )
docs.oracle.com
'language > java' 카테고리의 다른 글
[Java] Reflection을 이용하여 invoke() 로 메소드 동적호출 (0) | 2023.06.11 |
---|---|
[Java] System.arraycopy 와 Array.copyOfRange (0) | 2023.06.06 |
[JAVA/자바] 문자열 인코딩 변환 - String getBytes() (0) | 2022.12.15 |
[Java] Long 자료형을 Integer로 형변환 : java.lang.Long cannot be cast to class java.lang.Integer (0) | 2022.05.27 |
[Java] request.getRequestURI(), request.getContextPath() 등 url 주소 가져오는 함수 (0) | 2022.03.04 |