比较器比较内部列表字段

时间:2019-10-09 15:17:16

标签: java collections java-8 java-stream comparator

我有这样的模特

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 个答案:

答案 0 :(得分: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'