我正在尝试编写返回最富有员工的流。
Optional<User> getRichestEmployee() {
return getUserStream()
.flatMap(user -> user.getAccounts().stream())
.map(this::getAccountAmountInPLN)
.sorted(Comparator.reverseOrder())
.findFirst();
}
我的方法getAccounts()
返回 List<Account>
我的方法getAccountAmountInPLN
看起来像这样:
BigDecimal getAccountAmountInPLN(final Account account) {
return account
.getAmount()
.multiply(BigDecimal.valueOf(account.getCurrency().rate))
.round(new MathContext(4, RoundingMode.HALF_UP));
}
我的问题是,getRichestEmployee()
返回 Optional<BigDecimal>
.
我无法return
最富有的员工。在流中运行时,我无法访问 User
对象。如何返回用户?
最佳答案
我假设您是通过查找金额最高的帐户来计算用户的财富。
首先创建一个额外的方法来从用户那里获取金额:
public BigDecimal getUserMaxAmount(User user) {
return user
.getAccounts()
.stream()
.map(this::getAccountAmountInPLN)
.max(Comparator.naturalOrder())
.orElse(BigDecimal.ZERO); //if user has no account I default to 0
}
然后你就可以像这样使用它了:
Optional<User> getRichestEmployee() {
return getUserStream()
.sorted(Comparator.comparing(this::getUserMaxAmount, Comparator.reverseOrder()))
.findFirst();
}
或者更简单:
Optional<User> getRichestEmployee() {
return getUserStream().max(Comparator.comparing(this::getUserMaxAmount));
}
如果您的目的是通过对所有金额求和来计算用户的财富,则应通过对金额求和将流减少为单个值:
public BigDecimal getUserTotalAmount(User user) { //instead of getUserMaxAmount
return user
.getAccounts()
.stream()
.map(this::getAccountAmountInPLN)
.reduce(BigDecimal.ZERO, BigDecimal::add);
关于java - 返回 Optional<User> 而不是里面的 Optional<BigDecimal>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55050552/