SeouliteLab

[Java/자바] BinaryOperator.minBy() 메소드 사용 예제 본문

프로그래밍

[Java/자바] BinaryOperator.minBy() 메소드 사용 예제

Seoulite Lab 2024. 3. 13. 08:19

BinaryOperator.minBy() 메소드 소개

BinaryOperator.minBy() 메소드는 BinaryOperator 인터페이스의 정적 메소드로, 두 인수 중에서 더 작은 값을 반환하는 BinaryOperator를 생성합니다. 이 메소드는 Comparator를 사용하여 두 인수를 비교합니다.

예제 1: 두 정수 중에서 더 작은 값 찾기

import java.util.function.BinaryOperator;

BinaryOperator<Integer> minByInt = BinaryOperator.minBy(Integer::compareTo);
System.out.println("Min value: " + minByInt.apply(10, 5));

이 예제에서는 BinaryOperator.minBy()를 사용하여 두 정수 중에서 더 작은 값을 찾았습니다.

예제 2: 두 문자열 중에서 더 작은 값 찾기

import java.util.function.BinaryOperator;

BinaryOperator<String> minByString = BinaryOperator.minBy(String::compareTo);
System.out.println("Min value: " + minByString.apply("apple", "banana"));

이 예제에서는 BinaryOperator.minBy()를 사용하여 두 문자열 중에서 더 작은 값을 찾았습니다.

예제 3: Comparator.reverseOrder()와 함께 사용하기

import java.util.function.BinaryOperator;

BinaryOperator<Integer> minByReverse = BinaryOperator.minBy(Comparator.reverseOrder());
System.out.println("Min value: " + minByReverse.apply(7, 15));

이 예제에서는 BinaryOperator.minBy()를 사용하여 Comparator.reverseOrder()와 함께 두 정수 중에서 더 작은 값을 찾았습니다.

예제 4: 두 객체의 특정 속성 비교하기

import java.util.function.BinaryOperator;

class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

BinaryOperator<Person> youngestPerson = BinaryOperator.minBy(Comparator.comparingInt(person -> person.age));
Person person1 = new Person("John", 30);
Person person2 = new Person("Alice", 25);
System.out.println("Youngest person: " + youngestPerson.apply(person1, person2).name);

이 예제에서는 BinaryOperator.minBy()를 사용하여 두 Person 객체 중에서 나이가 어린 사람을 찾았습니다.

예제 5: null 처리하기

import java.util.function.BinaryOperator;

BinaryOperator<String> minByStringWithNull = BinaryOperator.minBy(Comparator.naturalOrder());
System.out.println("Min value: " + minByStringWithNull.apply("apple", null));

이 예제에서는 BinaryOperator.minBy()를 사용하여 null 값을 처리하면서 두 문자열 중에서 더 작은 값을 찾았습니다.

예제 6: Optional을 사용하여 두 값 중에서 더 작은 값 찾기

import java.util.Optional;
import java.util.function.BinaryOperator;

BinaryOperator<Integer> minByOptional = BinaryOperator.minBy(Integer::compareTo);
Optional<Integer> result = Optional.ofNullable(minByOptional.apply(20, null));
result.ifPresent(value -> System.out.println("Min value: " + value));

이 예제에서는 BinaryOperator.minBy()를 사용하여 Optional을 통해 null 값을 처리하고, 두 정수 중에서 더 작은 값을 찾았습니다.