I want to iterate through the list of Accounts, and sum up the Double credit amount using Java 8 lambda feature. Any ideas?
import lombok.*;
import java.util.List;
@Data
public class Account {
private Double amount;
@Getter(AccessLevel.NONE)
private Boolean active;
private String companyCode;
private Long accountNumber;
public Boolean isActiveAccount() {
return active;
}
}
I have a List of Accounts, I want to sum the credit amount using the Lambda Java 1.8 feature, how do I go about that, instead of the traditional approach that I have shown below?
//Lets pretend that the list has 3000 account-elements.
List<Account> accountsList = new ArrayList<>();
Double totalAmount = 0.0;
for (Account account : accountsList) {
Double accAmountList = account.getAmount();
if(null != accAmountList) totalAmount += accAmountList;
}
Make a stream out of the list, map to a list of double values
total=accountList.stream()
.filter(account ->account!=null&&
account.getAmount()!=null).mapToDouble(Account::getAmount)
.sum()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With