我有一节课如下
class Account{
String Name;
int amount;
}
Run Code Online (Sandbox Code Playgroud)
如果我有一个列表,List<Account>那么我怎样才能从这个名单总量不使用任何循环像for或foreach?
您可以使用创建帐户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.