java object values,从Java Object计算值?

这篇博客展示了如何利用Java 8的Stream API从一个PaymentDetailsItem对象的列表中提取并计算所有条目的总金额。通过调用map和reduce方法,可以方便地将每个对象的amount属性转换为浮点数并求和。示例代码详细解释了整个过程,并提供了两种不同的实现方式。
摘要由CSDN通过智能技术生成

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;

}

............

}

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

解决方案

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 payments = new ArrayList<>();

payments.add(payment);

payments.add(payment2);

List 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());

}

Remember to implement the getter for the amount attribute.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值