有效地多次迭代地图

时间:2013-03-09 18:04:37

标签: java collections

我有一个cookie管理器类,用于在域中存储域名列表。大部分时间尺寸将保持在100以下。

Map<String, CookieList> cookieMap;

每次我为连接设置cookie时,都需要遍历所有域(String),检查它是否可接受,然后插入CookieList。我将多次遍历地图。我有一个单独的列表,包含域并搜索,然后通过密钥获取CookieList

List<String> domainList;

// host is from the connection being set up
for (String domain : domainList) {
    if (host.contains(domain)) {
        CookieList list = cookieMap.get(domain);
        // set up cookies
    }
}

由于我使用contains,我无法直接从cookieMap获取密钥。这是一个好方法还是我应该迭代Map的EntrySet?如果是这样,LinkedHashMap在这个例子中会不错?

3 个答案:

答案 0 :(得分:3)

您可以使用Map来获取域名,而不是维护ListMap.keySet

for (String domain : cookieMap.keySet()) {
    if (host.contains(domain)) {
        CookieList list = cookieMap.get(domain);
    }
}

这没有什么低效率,因为for循环是O(n),而对cookieMap的调用是O(1)。

答案 1 :(得分:1)

Map<String, CookieList>  coockieMap = new HashMap<String, CookieList>();
for (Map.Entry<Integer, CookieList> entry : coockieMap.entrySet()) {
    if (host.contains(entry.getKey())) {
        CookieList list = entry.getValue();
    }
}

希望这会对你有所帮助。

答案 2 :(得分:1)

我认为您的代码已经过优化,如果您愿意,可以使用

domainList.retainAll(hosts)
在你的for循环之前

,所以停止每个循环检查。有效地,您的代码将如下所示:

List<String> hostList = new ArrayList<String>(domainList); // we don't want to edit domains

hostList.retainAll(host);  

for (String hostEntry : hostList) { // I'd rename "host" so I can use it here
        CookieList list = cookieMap.get(hostEntry);
        // set up cookies
}