比较器比较内部列表字段 [英] Comparator comparing inner list field

查看:52
本文介绍了比较器比较内部列表字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的模特

class Person {
     Instant updateDate; // mandatory
     List<Account> accounts; // can be empty
}

class Account {
    Instant accountUpdateDate; // can be null
}  

假设我有一个人员列表(每个人的帐户列表都可以为空)

Suppose that I have a list of persons (each person contains account list that can be empty)

如何获取具有最大accountUpdateDate的人,否则我应该检索具有最大updateDate的人.

How can I get the person with max accountUpdateDate, otherwise I should retrieve the person with max 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 分离出两种功能,例如:

One way of doing that could be using orElseGet to separate out both the functionalities such as:

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'

这篇关于比较器比较内部列表字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆