Return Optional<User> 而不是里面的 Optional<BigDecimal>

Return Optional<User> instead of Optional<BigDecimal> which is inside

我正在尝试编写 return 最富有的员工的信息流。

Optional<User> getRichestEmployee() {
    return getUserStream()
        .flatMap(user -> user.getAccounts().stream())
        .map(this::getAccountAmountInPLN)
        .sorted(Comparator.reverseOrder())
        .findFirst();
}

我的方法getAccounts()returnsList<Account>

我的方法 getAccountAmountInPLN 如下所示:

BigDecimal getAccountAmountInPLN(final Account account) {
    return account
            .getAmount()
            .multiply(BigDecimal.valueOf(account.getCurrency().rate))
            .round(new MathContext(4, RoundingMode.HALF_UP));
}

我的问题是,getRichestEmployee() returns Optional<BigDecimal>

我不能return最富有的员工。 运行 在直播时,我无法访问 User 个对象。如何return一个用户?

制作您自己的比较器,不要将每个帐户映射到其余额:

Optional<User> getRichestEmployee() {
 return getUserStream()
    .flatMap(user -> user.getAccounts().stream())
    .sorted((a1, a2) -> this.getAccountAmountInPLN(a2).compareTo(this.getAccountAmountInPLN(a1)))
    // Assuming there's a getter for the account owner...
    .map(Account::getOwner) // replace with Account's getter for owner
    .findFirst();

我假设您是通过查找金额最高的帐户来计算用户的财富。

首先创建一个额外的方法来从用户那里获取金额:

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

首先,要找到最富有的员工,您需要对员工的账户金额求和。

其次,要查找总金额最大的员工,请使用 max(Comparator<? super T> comparator)

示例:

Optional<User> getRichestEmployee() {
    return getUserStream()
            .max(Comparator.comparing(this::getEmployeeAmountInPLN));
}

BigDecimal getEmployeeAmountInPLN(final User user) {
    return user.getAccounts()
            .stream()
            .map(this::getAccountAmountInPLN)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
}

BigDecimal getAccountAmountInPLN(final Account account) {
    return account
            .getAmount()
            .multiply(BigDecimal.valueOf(account.getCurrency().rate))
            .round(new MathContext(4, RoundingMode.HALF_UP));
}