[英]How to get the total value from an ArrayList where one is product and the other one is price?
I am trying to get the total value from all the products purchased of the Cart. 我试图从购物车中购买的所有产品中获得总价值。 This information came from an ArrayList but I am not sure if the code I am doing is correct.
此信息来自ArrayList,但是我不确定我正在执行的代码是否正确。
public class Cart {
// creating a new list every time so need to modify..it will hold the list
private List<CartLine> cartLineList = new ArrayList<>();
/**
*
* @return the actual cartline list
*/
public List<CartLine> getCartLineList() {
return cartLineList;
}
public double getTotalValue(List<CartLine> cartLineList)
{
//TODO implement the method
//return Products*Price
double results=0;
// for(CartLine cartLine: getCartLineList()){
//results += (cartLine.getQuantity()* cartLine.getProduct().getPrice());
//}
return results;
}
//more code here...
this what CartLine looks like 这就是CartLine的样子
public class CartLine { 公共类CartLine {
private Product product;
private int quantity;
public CartLine(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public double getSubtotal() {
return quantity * product.getPrice();
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
} }
If getQuantity
does returns the amount purchased, and .getProduct().getPrice()
returns the price of the item, then the summation code looks fine (only commented out). 如果
getQuantity
确实返回了购买的金额,并且.getProduct().getPrice()
返回了商品的价格,则总和代码看起来很好(仅注释掉了)。 Here's what it should look like: 它应该是这样的:
public double getTotalValue(List<CartLine> cartLineList) {
double results = 0;
for(CartLine cartLine: getCartLineList()){
results += (cartLine.getQuantity() * cartLine.getProduct().getPrice());
}
return results;
}
It would be helpful if you showed us what CartLine
is. 如果您向我们展示了什么是
CartLine
这将很有帮助。 Could there be different products with different prices in the same CartLine
instance? 同一
CartLine
实例中可以有不同价格的不同产品吗?
The same answer but using lambdas 相同的答案,但使用lambdas
Collector<CartLine, double[], double[]> productSumCollector = Collector.of(
() -> new double[1],
(result, cartLine) -> result[0] += (cartLine.getQuantity() * cartLine.getProduct().getPrice()),
(result1, result2) -> {
result1[0] += result2[0];
return result1;
}
);
return Arrays.stream(cartLines).collect(productSumCollector)[0];
For reference see https://www.deadcoderising.com/2017-03-07-java-8-creating-a-custom-collector-for-your-stream/ 有关参考,请参见https://www.deadcoderising.com/2017-03-07-java-8-creating-a-custom-collector-for-your-stream/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.