一個(gè)對(duì)象有三個(gè)日期屬性,求這個(gè)對(duì)象集合中三個(gè)日期分別最晚的三個(gè)對(duì)象

import java.util.List;

import java.util.Optional;

// 一個(gè)對(duì)象有三個(gè)日期屬性

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(); // 假設(shè)這個(gè)方法返回了你的對(duì)象列表

? ? ? ? // 獲取date1最晚的對(duì)象

????????MaterialPurchase latestDate1? = findLatestByDate(materialPurchaseExList, "date1");

? ????? // 獲取date2最晚的對(duì)象

? ? ? ? MaterialPurchase latestDate2? = findLatestByDate(materialPurchaseExList, "date2");

? ????? // 獲取date3最晚的對(duì)象

? ? ? ? MaterialPurchase latestDate3? = findLatestByDate(materialPurchaseExList, "date3");

? ? ? ? // 打印結(jié)果

? ? ? ? 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);

? ? }

? ? // 假設(shè)這個(gè)方法返回了你的對(duì)象列表

? ? private static List<MaterialPurchase> getMaterialPurchaseList() {

? ? ? ? // 這里應(yīng)該返回實(shí)際的MaterialPurchase對(duì)象列表

? ? ? ? return null;

? ? }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容