Guava SetMultimap is not serializable (due to non-serializable WrappedSet)

I often use the java series, which is very useful for storing a complete hierarchy of objects.

When trying to serialize SetMultimap, I have an exception saying that AbstractMultimap.WrappedSet is not serializable.

How do guava users deal with this problem?

Thanks in advance,

+1
source share
2 answers

Representations of multimar elements (for example, collections returned from get methods, asMap representations, etc.) cannot intentionally be serialized. However, it is not true that the implementation of SetMultimap will not be serialized because of this. All the SetMultimap implementations that Guava provides are actually serializable ... these are just partial collections for them that are not.

If you need to serialize one of these collections, you must explicitly copy it to a regular collection:

 Set<Foo> foo = Sets.newHashSet(multimap.get(someKey)); 
+7
source

Change Therefore, looking at the source of AbstractMultimap , the returned Map is an AsMap or SortedAsMap , none of which are serializable. I would suggest creating a new HashMap and use the putAll method, passing in the Multimap.asMap() result. HashMap is serializable.

 HashMap myMap = new HashMap(); myMap.putAll(myMultimap.asMap()); 
0
source

All Articles