Java 计算列表中对象的所有金额
我将此Java对象存储在一个列表中:Java 计算列表中对象的所有金额,java,Java,我将此Java对象存储在一个列表中: public class ExpressCheckout { String currency; float amount; int quantity; String name; String description; ....... } 如何将每个对象的所有金额值计入列表?执行以下操作: public float sumAmounts(List<ExpressCheckout> myList){ fl
public class ExpressCheckout
{
String currency;
float amount;
int quantity;
String name;
String description;
.......
}
如何将每个对象的所有金额值计入列表?执行以下操作:
public float sumAmounts(List<ExpressCheckout> myList){
float total = 0.0f;
for(ExpressCheckout item : myList){
total += item.getAmount();
}
return total;
}
只需将它们放入for或foreach和sum amounts中即可如果您使用的是Java 8,一种非常简单的流技术是:
list.stream().mapToDouble(ExpressCheckout::getAmount).sum();
注意,我使用Java8,并在逻辑上假设当您有多种货币时,您不能简单地将它们全部相加。您可能需要按货币和金额分组。这给了你一个公平的想法
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class SomeClass {
protected class ExpressCheckout {
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
String currency;
float amount;
int quantity;
String name;
String description;
public ExpressCheckout(String currency, float amount, int quantity, String name, String description) {
this.currency = currency;
this.amount = amount;
this.quantity = quantity;
this.name = name;
this.description = description;
}
}
public static void main(String[] args) {
List<ExpressCheckout> expressCheckouts = new ArrayList<ExpressCheckout>();
ExpressCheckout co1 = new SomeClass().new ExpressCheckout("USD", 20.01f, 2, "Item1", "Some item");
ExpressCheckout co2 = new SomeClass().new ExpressCheckout("USD", 2.0f, 2, "Item1", "Some item");
ExpressCheckout co3 = new SomeClass().new ExpressCheckout("INR", 100.01f, 2, "Item1", "Some item");
ExpressCheckout co4 = new SomeClass().new ExpressCheckout("INR", 100.01f, 2, "Item1", "Some item");
ExpressCheckout co5 = new SomeClass().new ExpressCheckout("INR", 200.01f, 2, "Item1", "Some item");
expressCheckouts.add(co1);
expressCheckouts.add(co2);
expressCheckouts.add(co3);
expressCheckouts.add(co4);
expressCheckouts.add(co5);
System.out
.println(expressCheckouts.stream().collect(Collectors.groupingBy(SomeClass.ExpressCheckout::getCurrency,
Collectors.summingDouble(SomeClass.ExpressCheckout::getAmount))));
}
}
我需要浮点数的总值。我将其更改为list.stream.mapToFloatExpressCheckout::getAmount.sum;但是我得到的非静态方法getAmount不能从静态上下文引用