【问题标题】:Comparator comparing inner list field比较器比较内部列表字段
【发布时间】:2020-02-06 23:28:55
【问题描述】:

我有一个这样的模型

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

【问题讨论】:

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


    【解决方案1】:

    这样做的一种方法是使用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'
    

    【讨论】:

    • 谢谢,我试试看
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 2011-05-12
    • 2013-12-29
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多