37 lines
1011 B
Java
37 lines
1011 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 StreamExample17 {
|
||
|
public static void main(String[] args) {
|
||
|
List<Person> people = Arrays.asList(
|
||
|
new Person("Alice", 30),
|
||
|
new Person("Bob", 25),
|
||
|
new Person("Charlie", 35)
|
||
|
);
|
||
|
|
||
|
// 使用 Collectors.minBy 找到年龄最小的人
|
||
|
Optional<Person> youngest = people.stream()
|
||
|
.collect(Collectors.minBy(Comparator.comparingInt(Person::getAge)));
|
||
|
|
||
|
youngest.ifPresent(person ->
|
||
|
System.out.println("Youngest 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;
|
||
|
}
|
||
|
}
|
||
|
}
|