我一直在做学校作业,但是坚持了两天。
目标:
我得到的代码:
/**
* (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;
}
我很想听听您的正确执行情况。这里的课程是关于地图和集合的,因此考虑到那些实现建议将不胜感激!
您处在正确的轨道上,但您需要仔细考虑首次找到邮政编码/产品组合时发生的情况。
有很多Map
方法可以在更高版本的Java中简化此操作。我将在这里使用它们,但是如果您必须使用早期版本,则需要扩展其中一些语句。
类似于以下内容:
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);
}));
希望有意义-询问是否。
我认为您要将if语句移到for循环的开头,并且仅在该邮政编码尚不存在的情况下才创建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);
}