37 lines
1005 B
Java
37 lines
1005 B
Java
package stream;
|
|
|
|
import lombok.Getter;
|
|
|
|
import java.util.Arrays;
|
|
import java.util.Comparator;
|
|
import java.util.List;
|
|
import java.util.Optional;
|
|
import java.util.stream.Collectors;
|
|
|
|
public class StreamExample18 {
|
|
public static void main(String[] args) {
|
|
List<Person> people = Arrays.asList(
|
|
new Person("Alice", 30),
|
|
new Person("Bob", 25),
|
|
new Person("Charlie", 35)
|
|
);
|
|
|
|
// 使用 Collectors.maxBy 找到年龄最大的人
|
|
Optional<Person> oldest = people.stream()
|
|
.collect(Collectors.maxBy(Comparator.comparingInt(Person::getAge)));
|
|
|
|
oldest.ifPresent(person ->
|
|
System.out.println("Oldest Person: " + person.getName() + ", Age: " + person.getAge()));
|
|
}
|
|
|
|
@Getter
|
|
static class Person {
|
|
private final String name;
|
|
private final int age;
|
|
|
|
public Person(String name, int age) {
|
|
this.name = name;
|
|
this.age = age;
|
|
}
|
|
}
|
|
} |