[英]Java school project issue with Maps
我一直在做学校作业。
目标:
我给出的代码:
/**
* (DIFFICULT!!!)
* calculates a map of most bought products per zip code that is also ordered by zip code
* if multiple products have the same maximum count, just pick one.
* @return
*/
public Map<String, Product> mostBoughtProductByZipCode() {
Map<String, Product> mostBought = null;
// TODO create an appropriate data structure for the mostBought and calculate its contents
return mostBought;
}
我一直在尝试在 Map 中使用 Map 但在实施时遇到问题。 这远未完成,根本无法编译。
/**
* (DIFFICULT!!!)
* calculates a map of most bought products per zip code that is also ordered by zip code
* if multiple products have the same maximum count, just pick one.
* @return
*/
public Map<String, Product> mostBoughtProductByZipCode() {
Map<String, Product> mostBought = null;
Map<String, Map<Product, Integer>> zipCodeProducts = new HashMap<>();
for (Customer customer : this.customers) {
String tmp = customer.getZipCode();
Map<Product, Integer> tmpMap = new HashMap<>();
for (Purchase purchase: customer.getItems()) {
tmpMap.put(purchase.getProduct(),purchase.getAmount());
}
if (!zipCodeProducts.containsKey(tmp)){
zipCodeProducts.put(tmp, tmpMap);
} else {
???
}
}
// TODO create an appropriate data structure for the mostBought and calculate its contents
return mostBought;
}
我可以采取哪些步骤来修复此实施? 我只是在寻找提示而不是完整的解决方案。
我认为您想将 if 语句移至 for 循环的开头,并且仅在该 zip 代码不存在时才创建tmpMap
。 如果它已经存在,只需使用现有的并使用产品和数量进行更新。
for (Customer customer : this.customers) {
String tmp = customer.getZipCode();
Map<Product, Integer> tmpMap;
if (!zipCodeProducts.containsKey(tmp)){
tmpMap = new HashMap<Product, Integer>();
} else {
tmpMap = zipCodeProducts.get(tmp);
}
for (Purchase purchase: customer.getItems()) {
if (!tmpMap.containsKey(purchase.getProduct())) {
tmpMap.put(purchase.getProduct(),purchase.getAmount());
} else {
tmpMap.put(purchase.getProduct(), tmpMap.get(purchase.getProduct()) + purchase.getAmount());
}
}
zipCodeProducts.put(tmp, tmpMap);
}
您走在正确的轨道上,但您需要考虑第一次找到 zip 代码/产品组合时会发生什么。
在 Java 的后续版本中,有相当多的Map
方法可以使这更容易。 我将在这里使用它们,但如果您必须使用早期版本,那么您需要扩展其中的一些语句。
类似于以下内容:
Map<String, Map<Product, Integer>> zipCodeProducts = new HashMap<>();
for (Customer customer: customers) {
Map<Product,Integer> productCounts = zipCodeProducts.computeIfAbsent(customer.getZipCode(), () -> new HashMap<>());
for (Purchase purchase: customer.getItems()) {
productCounts.merge(purchase.getProduct(), 1, Integer::sum);
}
}
获得最高计数的产品应该相对简单:
Map<String,Integer> maxProducts = new HashMap<>();
zipCodeProducts.forEach((zc, pc) -> pc.forEach((pr, n) -> {
if (!maxProducts.contains(zc) || n > pc.get(maxProducts.get(zc)))
maxProducts.put(zc, pr);
}));
希望这是有道理的 - 如果没有,请询问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.