Java:Guava 多重映射,put-Method 覆盖具有相同键的条目

标签 java guava multimap

我有一个关于 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.

文档位于http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/Multimap.html#put(K,V)说的是:

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/

相关文章:

Java优先级队列

c++ - 使用迭代器打印 multimap

java - 计数器不会在 AsyncTask 的新实例中重新启动

java - Java 中的过滤、排序和限制不可修改列表

java - 管理用户、他们的角色、模块和权限的更合适的方法是什么?

java - 使用 Guava 的基础知识

java - Java 中具有 Long 或 AtomicLong 值的多键映射

c - C 中多重映射的任何良好实现?

java - Hibernate 对 group by 的查询

java - 在 junit 上执行 easymock 时出现断言错误