如何使用Java 8 Streams来计算运行余额

时间:2022-06-04 21:20:25

Please help me convert following calculation to streams

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

I have list of Transactions

我有交易清单

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

I am doing following operation to calculate original balance before each transaction happened. Note negative transaction means money added to the account

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

  @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);
    }

And i have the output as follows

我的输出如下

calculated

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

1 个解决方案

#1


1  

There's not going to be much improved but you could use IntStream along with a forEach and do something as such:

不会有太大的改进,但你可以使用IntStream和forEach并做这样的事情:

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);
}

#1


1  

There's not going to be much improved but you could use IntStream along with a forEach and do something as such:

不会有太大的改进,但你可以使用IntStream和forEach并做这样的事情:

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);
}