Java 8 Stream API: 按照日期字段倒序排序并获取第一个对象
使用 Java 8 Stream API 按照日期字段倒序排序并获取第一个对象
假设有一个对象类为 Person,其中包含一个日期类型的字段 birthDate,我们要对一个 Person 对象的集合 List
1. 定义 Person 类
import java.util.Date;
public class Person {
private String name;
private Date birthDate;
public Person(String name, Date birthDate) {
this.name = name;
this.birthDate = birthDate;
}
public String getName() {
return name;
}
public Date getBirthDate() {
return birthDate;
}
}
2. 使用 Stream API 进行排序和获取第一个对象
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 创建 Person 对象的集合
List<Person> persons = new ArrayList<>();
persons.add(new Person('Alice', new Date(2000, 1, 1)));
persons.add(new Person('Bob', new Date(1999, 2, 2)));
persons.add(new Person('Charlie', new Date(2001, 3, 3)));
// 根据 birthDate 字段倒序排序
Person firstPerson = persons.stream()
.sorted(Comparator.comparing(Person::getBirthDate).reversed())
.findFirst()
.orElse(null);
// 输出第一个对象的信息
if (firstPerson != null) {
System.out.println('First person: ' + firstPerson.getName() + ', ' + firstPerson.getBirthDate());
} else {
System.out.println('The collection is empty.');
}
}
}
解释:
persons.stream():创建 Person 对象集合的 Stream。sorted(Comparator.comparing(Person::getBirthDate).reversed()):使用 Comparator 对 Stream 中的 Person 对象进行排序。comparing(Person::getBirthDate)指定排序依据为 birthDate 字段,reversed()将排序顺序改为倒序。findFirst():从排序后的 Stream 中获取第一个元素。orElse(null):如果 Stream 为空,则返回 null。
运行结果:
First person: Charlie, Sun Apr 03 00:00:00 CST 3901
说明: 排序和取出第一个对象的操作成功。
原文地址: https://www.cveoy.top/t/topic/qe33 著作权归作者所有。请勿转载和采集!