【问题标题】:Sum of int from list of object [duplicate]对象列表中的 int 总和 [重复]
【发布时间】:2015-12-15 12:21:36
【问题描述】:

我有一门课如下

class Account{
    String Name;
    int amount;
}

如果我有一个List<Account> 的列表,那么如何在不使用forforeach 之类的循环的情况下从该列表中获取总金额?

【问题讨论】:

    标签: java java-8


    【解决方案1】:

    如果您不介意使用第三方库,可以在 Eclipse Collections 中找到 sumOfInt。它返回 long 而不是 int,因此溢出的可能性要小得多。

    您可以在 Iterate 类上使用静态实用程序方法,该方法适用于任何 java.lang.Iterable 类型,如下所示:

    List<Account> accounts = new ArrayList<>();
    long sum = Iterate.sumOfInt(accounts, Account::getAmount);
    

    或者你如果你的列表是MutableList,你可以使用列表上直接可用的方法。

    MutableList<Account> accounts = Lists.mutable.empty();
    long sum = accounts.sumOfInt(Account::getAmount);
    

    注意:我是 Eclipse Collections 的提交者

    【讨论】:

    • 如果有人关心溢出,.mapToLong(Account::getAmount).sum().collect(summingLong(Account::getAmount)) 也可以。
    【解决方案2】:

    您可以使用stream() 创建您的帐户流,使用mapToInt 将该流映射到每个帐户的金额,然后使用IntStream.sum() 对生成的IntStream 求和。

    List<Account> accounts = new ArrayList<>();
    int totalAmount = accounts.stream().mapToInt(Account::getAmount).sum();
    

    此代码假定amount 有一个getter getAmount

    【讨论】:

    • 是的,我更新了我的问题
    猜你喜欢
    • 2022-01-24
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 2012-05-06
    • 2017-02-09
    • 2021-09-21
    相关资源
    最近更新 更多