一尘不染

从Java对象计数值?

java

我有一个用于存储项目的Java对象:

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){
        this.name = name;
        this.amount = amount;
        this.quantity = quantity;
        this.currencyID = currencyID;
    }

    ............
}

我使用一个列表来存储几个对象。如何将每个对象存储区中的总数汇总到列表中?


阅读 193

收藏
2020-12-03

共1个答案

一尘不染

您可以利用Java 8 Stream API并实现如下所示的内容:

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<>();
    payments.add(payment);
    payments.add(payment2);

    List<String> amounts = payments.stream().map(PaymentDetailsItem::getAmount).collect(Collectors.toList());
    System.out.println("Here we have the extracted List of amounts: " + amounts);

    String totalAmount = amounts.stream()
            .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: " + payments.stream().map(PaymentDetailsItem::getAmount)
            .reduce((amount1, amount2) -> String.valueOf(Float.valueOf(amount1) + Float.valueOf(amount2))).get());
}

记住要为amount属性实现getter。

2020-12-03