如何使用Java 8 Streams来计算运行平衡

时间:2017-12-17 18:44:24

标签: java java-stream

请帮我将以下计算转换为流

我有交易清单

class Transaction
{
  String id;
  Double amount;
  Double balance;
}

before calculation / input

amount   balance
100.0    null
-50.0    null
100.0    null
-100.0   null
200.0    null

我正在进行以下操作,以便在每次交易发生前计算原始余额。注意负面交易是指添加到账户的资金

  @Test
    public void runningBalanceWithoutUpdatingCurrent(){
        Double current=300d;
        for (int i = 0; i < transactions.size(); i++) {
            Transaction transaction = transactions.get(i);
           if(i==0)
            transaction.setBalance(current + transaction.getAmount());
           else
               transaction.setBalance(transactions.get(i-1).getBalance()+transaction.getAmount());
        }
        System.out.println();
        System.out.println("calculated");
        print(transactions);
    }

我的输出如下

calculated

amount   balance
100.0    400.0
-50.0    350.0
100.0    450.0
-100.0   350.0
200.0    550.0

1 个答案:

答案 0 :(得分:1)

不会有太大改进,但您可以使用IntStreamforEach并执行以下操作:

public void runningBalanceWithoutUpdatingCurrent(){
        if(transactions.size() > 0){
            Transaction transaction = transactions.get(0);
            transaction.setBalance(300d + transaction.getAmount());
        }

        IntStream.range(1, transactions.size())
                 .forEach(i -> { 
                        Transaction t = transactions.get(i);
                        t.setBalance(transactions.get(i-1).getBalance() + t.getAmount());
                  });

        System.out.println();
        System.out.println("calculated");
        print(transactions);
}