BinaryOperator<T> 함수적 인터페이스는 minBy()maxBy() 정적 메소드를 제공한다.

Comparator를 이용해서 최대 T와 최소 T를 얻는다.

 

Comparator<T> 함수적 인터페이스

@FunctionalInterface
public interface Comparator<T> {
	public int compare(T o1, T o2); //추상메소드
}

compare() 메소드 : 첫 번째 매개값이 두 번째 매개값보다 작으면 음수, 같으면 0, 크면 양수를 리턴

 

fruit 클래스

package sec05.exam09_minby_maxby;

public class Fruit {
	public String name;
	public int price;
	
	public Fruit(String name, int price) {
		this.name = name;
		this.price = price;
	}
}

 

minBy(), maxBy() 정적 메소드

package sec05.exam09_minby_maxby;

import java.util.function.BinaryOperator;

public class OperatorMinByMaxByExample {
	public static void main(String[] args) {
		BinaryOperator<Fruit> binaryOperator;
		Fruit fruit;
		
		//Comparator의 익명 구현 객체
	 	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);
	 	//Integer.compare 메소드의 f1.price와 f2.price를 비교하여
	 	//f1.price < f2.price 이면 음수를 리턴
	 	//f1.price = f2.price 이면 0을 리턴
	 	//f1.price > f2.price 이면 양수를 리턴
	 	//딸기의 가격이 수박의 가격보다 작으므로 음수를 리턴 
	 	//minBy는 작은 것을 골라야 하므로 음수가 리턴되었으니 f1이 f2보다 작아서 음수가 리턴되었다고 인식
	 	//f1 선택
	 	
	 	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);
	 	//딸기의 가격이 수박의 가격보다 작으므로(수박의 가격이 더 큼) 음수를 리턴 
	 	//maxBy는 큰 것을 골라야 하므로 음수가 리턴되었으니 f1이 f2보다 작아서(f2가 f1보다 커서) 음수가 리턴되었다고 인식
	 	//f2 선택2
	 }
}
딸기
수박

+ Recent posts