import java.util.List;
import java.util.Optional;
// 一个对象有三个日期属性
class MaterialPurchase {
private Date date1;
private Date date2;
private Date date3;
// 省略getter和setter方法
}
public class Main {
public static void main(String[] args) {
List<MaterialPurchase> materialPurchaseExList = getMaterialPurchaseList(); // 假设这个方法返回了你的对象列表
// 获取date1最晚的对象
MaterialPurchase latestDate1 = findLatestByDate(materialPurchaseExList, "date1");
// 获取date2最晚的对象
MaterialPurchase latestDate2 = findLatestByDate(materialPurchaseExList, "date2");
// 获取date3最晚的对象
MaterialPurchase latestDate3 = findLatestByDate(materialPurchaseExList, "date3");
// 打印结果
System.out.println("latestDate1 : " + latestDate1 );
System.out.println("latestDate2 : " + latestDate2 );
System.out.println("latestDate3 : " + latestDate3 );
}
private static MaterialPurchase findLatestByDate(List<MaterialPurchase> list, String fieldName) {
Optional<MaterialPurchase> latest = list.stream()
.filter(item -> item != null && item.getClass().getDeclaredField(fieldName).getAnnotation(Nullable.class) != null)
.max((item1, item2) -> {
try {
Object date1 = item1.getClass().getDeclaredField(fieldName).get(item1);
Object date2 = item2.getClass().getDeclaredField(fieldName).get(item2);
if (date1 == null && date2 == null) return 0;
if (date1 == null) return -1;
if (date2 == null) return 1;
return ((Comparable) date1).compareTo(date2);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
});
return latest.orElse(null);
}
// 假设这个方法返回了你的对象列表
private static List<MaterialPurchase> getMaterialPurchaseList() {
// 这里应该返回实际的MaterialPurchase对象列表
return null;
}
}