将 Guava 的 ArrayListMultimap 转换为 Serializable Map
Convert Guava's ArrayListMultimap to Serializable Map
是否可以将 ArrayListMultimap
转换为 Serializable
Map
?当然键和值是可序列化的。
我知道 ArrayListMultimap
是可序列化的,但我想将其序列化为普通 Map
因为我不希望反序列化器必须了解 guava Multimaps。
我试过这个:
ArrayListMultimap<String, Integer> mmap = ArrayListMultimap.create();
mmap.put("key",1);
mmap.put("key",222222222);
ObjectOutput out = new ObjectOutputStream(new ByteArrayOutputStream());
//This works fine
out.writeObject(mmap);
Map<String, List<Integer>> map = Multimaps.asMap(mmap);
try {
out.writeObject(map);
} catch (NotSerializableException e){
//Multimaps.asMap is not Serializable, seems reasonable to me
}
ImmutableMap<String, List<Integer>> imap = ImmutableMap.copyOf(map);
//Will throw java.io.NotSerializableException: com.google.common.collect.AbstractMapBasedMultimap$RandomAccessWrappedList. Oh man!! why!??
out.writeObject(imap);
那么,有没有一种方法(希望是一种有效的方法)在可序列化映射中转换一个 ArrayListMultimap
,这是:一个带有可序列化列表的映射?
我正在使用 guava-18.0
您可以使用 Maps.transformValues(Map, Function)
:
将地图值转换为 Serializable
列表
imap = ImmutableMap.copyOf(Maps.transformValues(map, ImmutableList::copyOf));
是否可以将 ArrayListMultimap
转换为 Serializable
Map
?当然键和值是可序列化的。
我知道 ArrayListMultimap
是可序列化的,但我想将其序列化为普通 Map
因为我不希望反序列化器必须了解 guava Multimaps。
我试过这个:
ArrayListMultimap<String, Integer> mmap = ArrayListMultimap.create();
mmap.put("key",1);
mmap.put("key",222222222);
ObjectOutput out = new ObjectOutputStream(new ByteArrayOutputStream());
//This works fine
out.writeObject(mmap);
Map<String, List<Integer>> map = Multimaps.asMap(mmap);
try {
out.writeObject(map);
} catch (NotSerializableException e){
//Multimaps.asMap is not Serializable, seems reasonable to me
}
ImmutableMap<String, List<Integer>> imap = ImmutableMap.copyOf(map);
//Will throw java.io.NotSerializableException: com.google.common.collect.AbstractMapBasedMultimap$RandomAccessWrappedList. Oh man!! why!??
out.writeObject(imap);
那么,有没有一种方法(希望是一种有效的方法)在可序列化映射中转换一个 ArrayListMultimap
,这是:一个带有可序列化列表的映射?
我正在使用 guava-18.0
您可以使用 Maps.transformValues(Map, Function)
:
Serializable
列表
imap = ImmutableMap.copyOf(Maps.transformValues(map, ImmutableList::copyOf));