Operator 함수적 인터페이스 중 하나인 BinaryOperator<T>는 minBy( ), maxBy( )라는 정적 메서드를 제공합니다. 이 두 개의 메서드는 리턴 타입이 BinaryOperator<T> 입니다. 아래와 같이 해당 메서드 minBy( )와 maxBy( )는 파라미터로 Comparator<T>를 받게 되고, 이를 이용해서 최대 T 또는 최소 T를 얻는 BinaryOperator<T>를 리턴하는 구조입니다.
리턴 타입 | 정적 메서드 |
BinaryOperator<T> | minBy(Comparator<? super T> comparator) |
BinaryOperator<T> | maxBy(Comparator<? super T> comparator) |
그럼 결국 minBy 또는 maxBy 메서드 안 파라미터에는 Comparator<T>라는 함수적 인터페이스를 사용해야 하므로, 이 함수적 인터페이스 Comparator<T>에 미리 선언된 추상 메서드에 대한 람다식을 작성해 선언해 주면 됩니다. Comparator<T> 라는 함수적 인터페이스에 선언된 compare( ) 메서드는 다음과 같이 선언되어 있습니다.
@FunctionalInterface
public interface Comparator<T> {
public int compare(T o1, T o2);
}
여기서 compare라는 추상 메서드는 o1, 그리고 o2라는 파라미터를 사용합니다. 이 o1과 o2를 비교해서 o1이 작으면 음수, 동일하면 0, o1이 크면 양수를 리턴하는 compare( ) 메서드가 선언되어 있는 상태입니다. 이제 이를 감안하면, minBy 또는 maxBy 메서드를 사용할 때에는 다음과 같은 형태의 람다식을 작성하게 됩니다.
(o1, o2) -> { ...; return int값; }
만일 여기서, o1과 o2가 애초에 int 타입이라면 람다식에서 그냥 Integer.compare(int, int)를 사용해 주면 됩니다. Integer.compare( ) 메서드는 위에서 설명한 것과 마찬가지로 첫 번째 인자 값이 두 번째 인자값 보다 작으면 음수, 같으면 0, 크면 양수를 리턴합니다.
(o1, o2) -> Integer.compare(o1, o2);
아래와 같이 이를 활용해 예제를 작성해 보겠습니다.
public class Fruit {
public String name;
public int price;
public Fruit(String name, int price) {
this.name = name;
this.price = price;
}
}
import java.util.function.BinaryOperator;
public class ExampleMain {
public static void main(String[] args) {
BinaryOperator<Fruit> binaryOperator;
Fruit fruit;
binaryOperator = BinaryOperator.minBy( (f1, f2) -> Integer.compare(f1.price, f2.price) );
fruit = binaryOperator.apply(new Fruit("딸기", 6000), new Fruit("수박", 10000));
System.out.println(fruit.name);
binaryOperator = BinaryOperator.maxBy( (f1, f2) -> Integer.compare(f1.price, f2.price) );
fruit = binaryOperator.apply(new Fruit("딸기", 6000), new Fruit("수박", 10000));
System.out.println(fruit.name);
}
}
/* 출력
딸기
수박
*/
'Programming > JAVA' 카테고리의 다른 글
람다식(5) - 메서드 참조 2 : 정적 메서드, 인스턴스 메서드 참조 (0) | 2023.08.31 |
---|---|
람다식(5) - 메서드 참조 1 : 메서드 참조의 개념 (1) | 2023.08.31 |
람다식(4) - 표준 API의 함수적 인터페이스 8 : 디폴트 메서드 and(), or(), negate() 그리고 정적 메서드 isEqual() 2 (0) | 2023.08.17 |
람다식(4) - 표준 API의 함수적 인터페이스 8 : 디폴트 메서드 and(), or(), negate() 그리고 정적 메서드 isEqual() 1 (0) | 2023.08.04 |
람다식(4) - 표준 API의 함수적 인터페이스 7 : 디폴트 메서드 andThen(), compose() 3 (0) | 2023.07.31 |