对象列表中的int之和

Lyn*_*nAs 5 java java-8

我有一节课如下

class Account{
    String Name;
    int amount;
}
Run Code Online (Sandbox Code Playgroud)

如果我有一个列表,List<Account>那么我怎样才能从这个名单总量不使用任何循环像forforeach

Tun*_*aki 5

您可以使用创建帐户stream()流,将该流映射到每个帐户的使用mapToInt金额,并将结果IntStream使用总和IntStream.sum().

List<Account> accounts = new ArrayList<>();
int totalAmount = accounts.stream().mapToInt(Account::getAmount).sum();
Run Code Online (Sandbox Code Playgroud)

此代码假定有一个getter getAmountfor amount.