用java8将这个集合根据对象里的某个日期类型字段倒叙排序后取出第一个对象
假设有一个对象类为Person,其中包含一个日期类型的字段birthDate,我们要对一个Person对象的集合List
首先,需要定义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;
}
}
然后,我们可以使用Java 8的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.");
}
}
}
运行以上代码,将会输出:
First person: Charlie, Sun Apr 03 00:00:00 CST 3901
说明排序和取出第一个对象的操作成功
原文地址: https://www.cveoy.top/t/topic/ixNk 著作权归作者所有。请勿转载和采集!