我很难找到构造函数来构建可变Multimap
。我的代码是:
Multimap<String, DbEntity> multimapByKey = Multimaps.index(goodHosts, instanceGetKeyfunction);
...
multimapByKey.removeAll(someKey);
// throws
// java.lang.UnsupportedOperationException
// at com.google.common.collect.ImmutableListMultimap.removeAll(Unknown Source)
// at com.google.common.collect.ImmutableListMultimap.removeAll(Unknown Source)
由于索引返回ImmutableListMultimap
我真的无法修改它。但是,我无法在the official documentation上看到通过keyFunction for Multimaps进行分组的其他选项。
答案 0 :(得分:3)
您可以像索引函数一样创建一个返回可变Multimap
的方法,如下所示:
public static <K, V> Multimap<K, V> indexMutable(Iterable<V> values,
Function<? super V, K> function) {
// check null value, function
Multimap<K, V> map = ArrayListMultimap.create();
for (V v : values) {
// check null V
map.put(function.apply(v), v);
}
return map;
}
并像这样使用:
@Test
public void testMutableMap() throws Exception {
List<String> badGuys = Arrays.asList("Inky", "Blinky", "Pinky",
"Pinky", "Clyde");
Function<String, Integer> stringLengthFunction = new Function<String, Integer>() {
public Integer apply(String input) {
return input.length();
}
};
Multimap<Integer, String> multipmap = indexMutable(badGuys,
stringLengthFunction);
System.out.println(multipmap);
multipmap.clear();
System.out.println("It's mutable!");
for (String guy : badGuys) {
multipmap.get(stringLengthFunction.apply(guy)).add(guy);
}
System.out.println(multipmap);
}
它的输出:
{4=[Inky], 5=[Pinky, Pinky, Clyde], 6=[Blinky]}
It's mutable!
{4=[Inky], 5=[Pinky, Pinky, Clyde], 6=[Blinky]}
此示例与Multimaps#index
的Javadoc相同。