使用for循环(Java)

时间:2015-08-01 12:53:16

标签: java for-loop

我有一个清单:

List<FaAccount> accounts = someMethod();

此列表包含accountidcurrencybalance。现在我想按货币汇总余额(每种货币的余额总和)。我创建了包含currencybalance个变量的新课程。这只会将FaAccount的信息复制到FaAccountBalance

List<FaAccountBalance> aggr = new ArrayList<>();
for(FaAccount account : accounts){
            FaAccountBalance ag = new FaAccountBalance();
            ag.setCurrency(account.getCurrency());
            ag.setBalance(account.getBalance());
            aggr.add(ag);
}

我如何将(List}一个for循环或其他技术放入其中(以及{}}},以便表示每种货币的余额总和?

3 个答案:

答案 0 :(得分:1)

首先,您的设计并不理想,您有一些冗余。实际上,您明确地复制信息,这表明您应该拥有此数据并不清楚。我会建议这个更好的方法:

public class FaAccount {
    private final FaAccountBalance balance;
    private final int accountId;
}

public class FaAccountBalance {
    private float amount;
    private Currency currency;
}

聚合非常简单:

Map<Currency, Double> aggregation = new HashMap<>();
for (FaAccount account : accounts) {
   FaAccountBalance balance = account.getBalance();
   aggregation.put(balance.getCurrency(), aggregation.getOrDefault(0) + balance.getAmount());
}

最后,

List<FaAccountBalance> aggregatedBalances = 
    aggregation.entrySet()
               .map(entry -> new FaAccountBalance(entry.getKey(), entry.getValue()))
               .collect(Collectors.toList());

答案 1 :(得分:1)

您可以使用HashMap

在相同的for循环中执行此操作,而不是使用不同的for循环
List<FaAccountBalance> aggr = new ArrayList<>();
HashMap<String,Integer> map = new HashMap<>();
for(FaAccount account : accounts){
        String currency = account.getCurrency();
        int balance =account.getBalance();
        FaAccountBalance ag = new FaAccountBalance();
        ag.setCurrency(currency);
        ag.setBalance(balance);
        aggr.add(ag);        
        map.put(currency,map.getOrDefault(currency,0) + balance);
}

在此for循环之后,您将获得每种货币的汇总余额,只需将其打印为:

for(String currency: map.keySet()){
    System.out.println(currency + " : " + map.get(currency));
}

更新如果您想要BigDecimal,则不能只使用+添加add。您必须使用map.put(currency,map.getOrDefault(currency, BigDecimal.ZERO).add(new BigDecimal(balance)));

List< FaAcountBalance> result  = new LinkedList<>();
for(String currency: map.keySet()){
    result.add(new FaAcountBalance(currency,map.get(currency)));
}
return result;

如果要将其存储在List中,而不是打印hashmap内容,请将它们添加到列表中。

-r

答案 2 :(得分:1)

其他选项包括使用Collectors.groupingBy,然后只需将每个Map.Entry映射到FaAccountBalance并将其收集为列表:

final List<FaAccountBalance> accountBalances = 
    accounts
        .stream()
        .collect(Collectors.groupingBy(FaAccount::getCurrency, Collectors.summingInt(FaAccount::getBalance)))
        .entrySet()
        .stream()
        .map(entry -> {
            final FaAccountBalance f = new FaAccountBalance();
            f.setCurrency(entry.getKey());
            f.setBalance(entry.getValue());
            return f;
        }).collect(Collectors.toList());