Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of double value in a List using Lambda from Java 8 [duplicate]

Tags:

java

lambda

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;
}
like image 688
S34N Avatar asked Nov 03 '25 04:11

S34N


1 Answers

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()
like image 153
soorapadman Avatar answered Nov 04 '25 20:11

soorapadman