簡體   English   中英

比較器比較內部列表字段

[英]Comparator comparing inner list field

我有一個像這樣的 model

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

一種方法是使用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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM