gpt4 book ai didi

java - 使用 Map.putAll() 时覆盖

转载 作者:行者123 更新时间:2023-11-30 09:04:21 57 4
gpt4 key购买 nike

我在使用 Map.putAll() 时遇到了一些困难。它不是更新/添加特定记录到我的主 map ,而是覆盖条目:

  ConcurrentMap<String, ConcurrentHashMap<CardType, Card>> cache = new ConcurrentHashMap<String, ConcurrentHashMap<CardType, Card>>();

三个独立的 map 生成如下:

   ConcurrentMap<String, ConcurrentHashMap<CardType, Card>> businessCardCache = buildBusinesscardCacheValues(connection, getBusinessCards);
ConcurrentMap<String, ConcurrentHashMap<CardType, Card>> personalCardCache = buildPersonalcardCacheValues(connection, getPersonalCards);
ConcurrentMap<String, ConcurrentHashMap<CardType, Card>> socialCardCache = buildSocialcardCacheValues(connection, getSocialCard);
cache.putAll(businessCardCache);
cache.putAll(personalCardCache);
cache.putAll(socialCardCache);

应该发生的情况是,例如用户 ben 应该是 key ,他应该有个人业务和社交卡。事实上,他最终只得到了一张 socialCard,因为我认为它是最后运行的,因此会覆盖之前的。

我应该如何修改它?

谢谢

最佳答案

您当前对 cache 的初始化会导致 cache.putAll(personalCardCache); 替换由 cache.putAll(businessCardCache); 添加的值> 对于出现在两个映射中的键。

如果您希望缓存包含每个用户的所有卡片(取自所有 3 个输入映射),您应该以不同的方式初始化它:

for (String key : businessCardCache.keySet()) {
ConcurrentHashMap<CardType, Card> cards = null;
if (cache.containsKey(key) {
cards = cache.get(key);
} else {
cards = new ConcurrentHashMap<CardType, Card>();
}
cards.putAll (businessCardCache.get(key));
}

然后对其他 2 个 map 执行相同的操作。

关于java - 使用 Map.putAll() 时覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25267176/

57 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com