我有一个关于 Guava 多重 map 的问题。该文档在某种程度上含糊不清。对于multimaps中的put-Method,eclise给我这样的解释:
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.
Stores a key-value pair in the multimap. Some multimap implementations allow duplicate key-value pairs, in which case put always adds a new key-value pair and increases the multimap size by 1. Other implementations prohibit duplicates, and storing a key-value pair that's already in the multimap has no effect.
Eclipse 中的解释很有意义,并解释了为什么我的值被覆盖,但文档说可以为一个键存储多个值。
我向您展示我的一段代码:
public class Updatemanager {
static Map<String,Multimap<String,Values>> updateMap = new HashMap<String, Multimap<String, Values>>();
public static void collectUpdates(String name, String categorie, Values v)
{
Multimap<String, Values> mm = HashMultimap.create();
mm.put(categorie, v);
updateMap.put(name, mm);
}
我想要的输出如下所示:
{name={categorie1=[Values], categorie2 = [Values]}
现在的情况是它总是会覆盖某个特定键的 updateMap 的内容。我怎样才能做到现在覆盖并仅添加到 map 中?
提前非常感谢。
最佳答案
Multimap
工作得很好,但您要将 updateMap
中的 Multimap
替换为全新的 Multimap
> 没有条目,然后向其中添加一个条目。
看起来像你想要的
updateMap.get(name).put(categorie, v);
或者,如果您之前没有见过name
,则需要创建一个新的Multimap
,
if (!updateMap.containsKey(name)) {
updateMap.put(name, HashMultimap.<String, Values>create());
}
updateMap.get(name).put(categorie, v);
关于Java:Guava 多重映射,put-Method 覆盖具有相同键的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19524311/