I am looking at this API ArrayListMultiMap
which implements the Serializable
interface. Does that mean I can serialize this object ? Are all Multimap objects serialized ?

- 292,901
- 67
- 465
- 588

- 358
- 5
- 6
2 Answers
The meaning of Serializable
is always the same: If an object isn't serializable, it can't be serialized. If it is, it may work or not... Especially in case of collections (including maps and multimaps), it depends on their content.
As an example, you can surely serialize ArrayList<String>
as ArrayList.class
is serializable and so is each member of the list. OTOH trying to serialize ArrayList<Object>
may or may not work: If all contained objects are e.g. strings, it will work. If any member is not serializable, you'll get an exception.
Does it mean I can serialize this object?
If all keys and values are serializable, you can.
Are all multiMap object serializable?
No, the interface Multimap
doesn't extend Serializable
, so there may be non-serializable implementation. Indeed, you can get such an instance via e.g. Multimaps.filterEntries
.

- 44,714
- 32
- 161
- 320
-
I agree with maartinus. Since I am using ArralyListMultiMap (which implements Serializable) and key and value in my case are String I should be able to Serialized. – Princesh Dec 13 '12 at 18:40
ArrayListMultimap
and HashMultimap
are Serializable
BUT the Collection
views (in asMap()
for example) are not.
This problem is answered here:
To use the map returned by asMap()
, you can re-create a new map and wrap the Multimap Collection
views into other collections (for example a Set
), that will make the new map Serializable
:
Multimap<MyClass, MyOtherClass> myMultiMap = HashMultimap.create();
// ... build your multimap
Map<MyClass, Set<MyOtherClass>> map = myMultiMap.asMap().entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
(entry) -> ImmutableSet.copyOf(entry.getValue())
));
Or java 7 compliant code:
Multimap<MyClass, MyOtherClass> myMultiMap = HashMultimap.create();
// ... build your multimap
Map<MyClass, Set<MyOtherClass>> map = Maps.newHashMap();
for (Map.Entry<MyClass, Collection<MyOtherClass>> entry :
myMultiMap.asMap().entrySet()) {
map.put(entry.getKey(), ImmutableSet.copyOf(entry.getValue()));
}

- 1
- 1

- 41
- 3