比较器比较内部列表字段

我有一个这样的模型


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


胡子哥哥
浏览 63回答 1
1回答

MM们

一种方法是使用orElseGet分离这两种功能,例如:Supplier<Person> supplyMaxUpdateDatePerson = () -> personList.stream()&nbsp; &nbsp; &nbsp; &nbsp; .max(Comparator.comparing(Person::getUpdateDate))&nbsp; &nbsp; &nbsp; &nbsp; .orElse(null); // or an identity value equivalent for 'Person'Person maxAccountUpdateDateOrElseUpdateDate = personList.stream()&nbsp; &nbsp; &nbsp; &nbsp; .flatMap(person -> person.getAccounts().stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(account -> new AbstractMap.SimpleEntry<>(person, account.getAccountUpdateDate())))&nbsp; &nbsp; &nbsp; &nbsp; .filter(entry -> entry.getValue() != null) // otherwise you would always have a result in max&nbsp; &nbsp; &nbsp; &nbsp; .max(Comparator.comparing(AbstractMap.SimpleEntry::getValue))&nbsp; &nbsp; &nbsp; &nbsp; .map(AbstractMap.SimpleEntry::getKey)&nbsp; &nbsp; &nbsp; &nbsp; .orElseGet(supplyMaxUpdateDatePerson); // invoked only when all 'accountUpdateDate' are 'null'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java