Peter Penzov Peter Penzov - 11 months ago 45
Java Question

Count values from Java Object?

I have this Java object which is used to store item:

public class PaymentDetailsItem
private String name;
private String amount;
private int quantity;
private String currencyID;

public PaymentDetailsItem(String name, String amount, int quantity, String currencyID){ = name;
this.amount = amount;
this.quantity = quantity;
this.currencyID = currencyID;


I use a List to store several Objects. How can I sum up the total amount from every object store into the List?

Answer Source

You could make use of Java 8 Stream API and implement something like this:

public static void main(String[] args) {
    PaymentDetailsItem payment = new PaymentDetailsItem("test", "100.00", 10, "1");
    PaymentDetailsItem payment2 = new PaymentDetailsItem("test number 2", "250.00", 10, "2");

    List<PaymentDetailsItem> payments = new ArrayList<>();

    List<String> amounts =;
    System.out.println("Here we have the extracted List of amounts: " + amounts);

    String totalAmount =
            .reduce((amount1, amount2) -> String.valueOf(Float.valueOf(amount1) + Float.valueOf(amount2))).get();
    System.out.println("Total amount obtained by using .reduce() upon the List of amounts: " + totalAmount);

    System.out.println("Or you can do everything at once: " +
            .reduce((amount1, amount2) -> String.valueOf(Float.valueOf(amount1) + Float.valueOf(amount2))).get());

Remember to implement the getter for the amount attribute.