示例代码:
import java.util.*;class Person {private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}public int getAge() {return age;}
}public class Main {public static void main(String[] args) {List<Person> personList = new ArrayList<>();personList.add(new Person("Alice", 25));personList.add(new Person("Bob", 30));personList.add(new Person("Charlie", 28));// 使用比较器来比较年龄属性Comparator<Person> ageComparator = Comparator.comparingInt(Person::getAge);// 找到年龄最大的人Person oldestPerson = Collections.max(personList, ageComparator);System.out.println("Name: " + oldestPerson.getName() + ", Age: " + oldestPerson.getAge());}
}
在这个例子中,ageComparator
使用 Comparator.comparingInt()
方法来创建一个比较器,以便根据年龄属性进行比较。然后,Collections.max()
方法使用这个比较器来找到年龄属性最大的那个 Person
对象。