javaで3つのオブジェクトのフィールドの大きさを比較する方法

オブジェクトのフィールドの値が大きい小さいを比較する場合は、オブジェクトのフィールドを比較することで大小を判定する必要があります。次のコード例は、3つのオブジェクトのあるフィールドの大小を比較しています。

import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        // 创建三个对象
        Person person1 = new Person("John", 25);
        Person person2 = new Person("Alice", 30);
        Person person3 = new Person("Bob", 20);

        // 比较三个对象的age字段大小
        int result = Comparator.comparingInt(Person::getAge)
                .compare(person1, person2);
        if (result > 0) {
            System.out.println(person1.getName() + "的age字段大于" + person2.getName() + "的age字段");
        } else if (result < 0) {
            System.out.println(person1.getName() + "的age字段小于" + person2.getName() + "的age字段");
        } else {
            System.out.println(person1.getName() + "的age字段等于" + person2.getName() + "的age字段");
        }
    }

    private static class Person {
        private String name;
        private int age;

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

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }
    }
}

上記のコードでは、Comparator.comparingIntを使用してageを比較するフィールドを指定する比較器Person::getAgeを作成します。そして、compareメソッドを使用してperson1とperson2オブジェクトのageフィールドの大小を比較し、その結果をresult変数に保存します。結果によってフィールドの大小関係を判断できます。

bannerAds