1 回答

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
一種方法是使用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'
添加回答
舉報(bào)