I got a question about guava multimaps. The documentation is somehow ambiguous. For the put-Method in multimaps, eclise give me this explanation:

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.

The documentation at http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/Multimap.html#put(K,V) says this:

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.

The explanation in eclipse makes sense and explains why my values are overwritten, but the documentation says its possible to store multiple values for one key.

I show you a piece of my code:

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);        
}

My desired output looks like this:

{name={categorie1=[Values], categorie2 = [Values]}

How it is right now it always overwrites the content of the updateMap for one particular key. How can I make it, that there is now overwriting and just adding to the map?

Thanks a lot in advance.

有帮助吗?

解决方案

The Multimap works just fine, but you're replacing the Multimap in updateMap with a completely new Multimap with no entries, and then adding an entry to that.

It looks like you want

 updateMap.get(name).put(categorie, v);

or, if you need to create a new Multimap if you haven't seen name before,

 if (!updateMap.containsKey(name)) {
   updateMap.put(name, HashMultimap.<String, Values>create());
 }
 updateMap.get(name).put(categorie, v);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top