重构HashMap的最快方法 [英] Fastest way to restructure a HashMap

查看:109
本文介绍了重构HashMap的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HashMap将公司映射到他们销售的产品的ArrayList,如下所示:

I have a HashMap that maps companies to an ArrayList of the products they sell, like so:

thiscompany --> [productA, productB...]
thatcompany --> [productC, productA...]

因此,生成给定的产品列表非常容易具体公司。请注意,多家公司可能会销售相同的产品。问题是,鉴于特定产品,我还需要找到所有销售它的公司。很快。这种查找可能会发生一次或多次。我想知道提供此功能的最有效方法。

Hence it is very easy to generate a list of products given a specific company. Note that multiple companies may sell the same product. The issue is that I also need to, given a specific product, find all the companies that sell it. And quickly. This sort of lookup may happen once, or multiple times. I am wondering the most efficient way to provide this functionality.

目前,我正在通过迭代每个ArrayList并将每个产品映射到其供应商来生成新的数据结构。这很昂贵,因为我必须检查我正在创建的HashMap是否每次添加之前都包含该产品作为键,而且它需要我获取每个ArrayList,添加新的供应商,删除旧的ArrayList然后映射每个条目的新的。我根本无法看到更快的方式,也许有人可以提供一些见解?

Currently I am generating a new data structure by iterating through each ArrayList and mapping each product to its vendor. This is expensive though, because I have to check to see whether the HashMap I am creating contains that product as a key each time before adding, plus it requires me to get the each ArrayList, add the new vendor, delete the old ArrayList then map the new one for each entry. I simply cannot see a faster way of doing this though, perhaps someone can provide me with some insight?

推荐答案

如何将ArrayList更改为HashSet。

How about changing the ArrayList to a HashSet.

List<String> findCompanies(Map<String,Set<String>> companyToProducts, String product) {
    List<String> companies = new ArrayList<String>();
    for (Map.Entry<String,Set<String>> entry : companyToProducts) {
        Set<String> products = entry.getValue();
        if (products.contains(product)) {
            companies.add(entry.getKey());
        }
    }
    return companies;
}

另一种常见方法是在数据库中使用带有列的表产品和公司专栏,然后做一个:

Another common approach would be to use a table in a database with a column for product and a column for company and then do a:

select distinct company from companyToProduct where product = 'cheese';

这篇关于重构HashMap的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆