我一直在做学校作业。

目标:


我要列出超市顾客名单
每个客户都有一个邮政编码和一个带有产品名称的Set,以及该客户购买的这些产品的数量。
我被要求返回一个地图(Sting = zipCode,Product = Product),该地图应包含邮政编码作为密钥以及该邮政编码最多出售的产品。


我得到的代码:

/**
 * (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;
}


我一直在尝试在地图中使用地图,但在实现此功能时遇到问题。这远未完成,根本无法编译。

/**
 * (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);
}));


希望有道理-询问是否可以。

10-08 04:37