Search code examples
javalambdajava-stream

How to add total amount from list of lists using the Java Stream API?


I have a class:

public class Customer{
private List<Order> orders;
private String name;
...
}
public class Order{
private long orderId;
private String customerId;
private double amount;
...
}

public class CustomerService{

@Autowired
private CustomerRepository customerRepo;

List<Customer> custList = customerRepo.findAllCustomers();

double amount = custList.stream().map(c -> {
return c.getOrders().stream().mapToDouble(o -> o.getAmount()).sum()}).findAny().get();

}

So I tried as like above in CustomerService. But the amount returned is only for the first item in the list. So in the same way how can I write to get the total amount of all the orders for that customer?

Any suggestions/input will be helpful.

Note: Sorry for any compile errors. I cannot copy my code and so I need to write in the question instead.


Solution

  • You use flatMap():

    double total = custList.stream()
            .flatMap(c -> c.getOrders().stream())
            .mapToDouble(Order::getAmount)
            .sum();
    

    Also note the use of method reference to get the amount from the order.