Assume a Person class:
public class Person {
private String name;
private int age;
// constructor, getters
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}
And a list of persons:
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 45),
new Person("Charlie", 40)
);
Using max() with Comparator
Person oldest = people.stream()
.max(Comparator.comparingInt(Person::getAge))
.orElse(null); // returns null if the list is empty
System.out.println("Oldest person: " + oldest.getName() + ", Age: " + oldest.getAge());
