java - 返回 Optional<User> 而不是里面的 Optional<BigDecimal>

标签 java java-8 functional-programming java-stream option-type

我正在尝试编写返回最富有员工的流。

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/

相关文章:

java - 我可以在 Java 8 中将 Clojure 函数用作 Lambda 吗?

design-patterns - CQS设计原理题: Implementing a Queue

java - JBox2D 无法创建世界,Vec2 和 Boolean 类型的参数不存在

java - 如何制作 Stream 的副本,以便在使用它时使用 Java 8 中的副本?

java - 如何从 Swing 组件中检索唯一的字符串?

java - 为什么我们需要 JOOQ 的 JOOL?

scala - 在函数式编程中查找列表列表中元素的位置

f# - F# 中的 mixin 或 trait

java - 将静态 java 对象用于软件组件

java - 在 JavaEE 中创建 Web 服务