gpt4 book ai didi

java - array List 重复和排序方法

转载 作者:行者123 更新时间:2023-12-01 17:05:11 25 4
gpt4 key购买 nike

此类捕获订单详细信息。

public class OrderDetails {
private int priceEach = 0;
private int quantityOrdered = 0;
private String productCode = null;

public OrderDetails(int priceEach, int quantityOrdered, String productCode) {
super();
this.priceEach = priceEach;
this.quantityOrdered = quantityOrdered;
this.productCode = productCode;
}

public int getPriceEach() {
return this.priceEach;
}

public int getQuantityOrdered() {
return this.quantityOrdered;
}

public String getProductCode() {
return this.productCode;
}

此类捕获产品

public class Products {
private String productName = null;
private String productCode = null;

public Products(String productName, String productCode) {
super();
this.productName = productName;
this.productCode = productCode;
}

public String getProductName() {
return this.productName;
}

public String getProductCode() {
return this.productCode;
}

}

我需要一种方法来计算按产品名称排序的每个产品产生的收入。请记住,该方法中的数组列表将有重复项,并且以不同的价格定价。该方法的输出应该没有重复项,并且经过排序,每个产品名称都有与其对应的收入。

这是我尝试过的方法,但没有给出正确的输出。该方法位于 Products 类中。

public int calaculateTotalCost(List<OrderDetails> orderDetails, List<Products> products, String productCode,
String productName) {
int sum = 0;

for (OrderDetails o : orderDetails) {
for (Products p : products)
if ((o.getProductCode() == productCode) && p.getProductName() == productName) {
sum += (o.getPriceEach() * o.getQuantityOrdered());
}

}

return sum;
}

最佳答案

你可以尝试这样的事情:

    public Map calaculateTotalCost(List<OrderDetails> orderDetails, List<Products> products) {
Map<String, Products> map = new LinkedHashMap<>();
Map<Products, Integer> revenue = new HashMap<>();

for (Products p : products) {
map.put(p.getProductCode(), p);
}

for (OrderDetails order : orderDetails) {
if (map.containsKey(order.getProductCode())) {
Products p = map.get(order.getProductCode());
revenue.put(p, revenue.getOrDefault(p, 0) + (order.getPriceEach() * order.getQuantityOrdered()));
}
}

return revenue.entrySet().stream().sorted(Entry.<Products, Integer>comparingByValue().reversed())
.sorted(Entry
.<Products, Integer>comparingByKey((p1, p2) -> p1.getProductName().compareTo(p2.productName)))
.collect(Collectors.toMap(k -> k, v -> v));
}

关于java - array List 重复和排序方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61470377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com