亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

比較器比較內部列表字段

比較器比較內部列表字段

胡子哥哥 2023-10-12 14:45:43
我有一個這樣的模型class Person {     Instant updateDate; // mandatory     List<Account> accounts; // can be empty}class Account {    Instant accountUpdateDate; // can be null}  假設我有一個人員列表(每個人都包含可以為空的帳戶列表)我怎樣才能獲得具有最大 accountUpdateDate 的人,否則我應該檢索具有最大 updateDate 的人。類似這樣的事情Comparator<Person> UPDATE_DATE_COMPARATOR = Comparator    .comparing(person -> person.getAccounts().stream().map(Account::getAccountUpdateDate)..., Comparator.nullsFirst(naturalOrder()))    .thenComparing(Person::getUpdateDate));Collections.max(personList, UPDATE_DATE_COMPARATOR);
查看完整描述

1 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

一種方法是使用orElseGet分離這兩種功能,例如:


Supplier<Person> supplyMaxUpdateDatePerson = () -> personList.stream()

        .max(Comparator.comparing(Person::getUpdateDate))

        .orElse(null); // or an identity value equivalent for 'Person'


Person maxAccountUpdateDateOrElseUpdateDate = personList.stream()

        .flatMap(person -> person.getAccounts().stream()

                .map(account -> new AbstractMap.SimpleEntry<>(person, account.getAccountUpdateDate())))

        .filter(entry -> entry.getValue() != null) // otherwise you would always have a result in max

        .max(Comparator.comparing(AbstractMap.SimpleEntry::getValue))

        .map(AbstractMap.SimpleEntry::getKey)

        .orElseGet(supplyMaxUpdateDatePerson); // invoked only when all 'accountUpdateDate' are 'null'



查看完整回答
反對 回復 2023-10-12
  • 1 回答
  • 0 關注
  • 97 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號