1 回答

TA贡献1886条经验 获得超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'
添加回答
举报