我将此Java对象存储在List:
中public class ExpressCheckout
{
String currency;
float amount;
int quantity;
String name;
String description;
.......
}
如何从每个对象中将所有金额计入List?
答案 0 :(得分:3)
做类似的事情:
public float sumAmounts(List<ExpressCheckout> myList){
float total = 0.0f;
for(ExpressCheckout item : myList){
total += item.getAmount();
}
return total;
}
只需将它们放在for
或foreach
和总金额
答案 1 :(得分:2)
如果您使用的是Java 8,那么使用流的非常简单的技术是:
list.stream().mapToDouble(ExpressCheckout::getAmount).sum();
答案 2 :(得分:0)
警告,我使用Java 8并从逻辑上假设当你有多种货币时,你不能简单地将它们全部加起来。您可能需要按货币和总和进行分组。这为你提供了一个合理的想法
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))));
}
}