从Java Object计算值? [英] Count values from Java Object?
本文介绍了从Java Object计算值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个用于存储项目的Java对象:
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){
this.name = name;
this.amount = amount;
this.quantity = quantity;
this.currencyID = currencyID;
}
............
}
我使用List来存储多个对象。如何将每个对象库中的总金额汇总到列表中?
I use a List to store several Objects. How can I sum up the total amount from every object store into the List?
推荐答案
您可以使用Java 8 Stream API并实现类似的东西:
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<>();
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());
}
请记住为金额属性实施getter。
Remember to implement the getter for the amount attribute.
这篇关于从Java Object计算值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文