本文介绍了如何使用非唯一值与Guava进行地图反演?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们如何用Guava做到这一点?注意在返回类型中存在 List< K>
,因为许多键可以映射到任何普通映射中的相同值。
How can we do that with Guava? Notice the presence of List<K>
in the return type since many keys can map to the same value in any normal map.
public static <K, V> Map<V, List<K>> inverse(Map<K, V> map){
Map<V, List<K>> result = new LinkedHashMap<V, List<K>>();
for (Map.Entry<K, V> entry : map.entrySet()) {
if(!result.containsKey(entry.getValue())){
result.put(entry.getValue(), new ArrayList<K>());
}
result.get(entry.getValue()).add(entry.getKey());
}
return result;
}
推荐答案
你可以这样做:
Map<K, V> map = ...;
ListMultimap<V, K> inverse = Multimaps.invertFrom(Multimaps.forMap(map),
ArrayListMultimap.<V,K>create());
注意,几乎任何时候你写 Map< K,List< V>
或地图< K,设置< V>>< / code>或某些这样的
ListMultimap< V>
或 SetMultimap< K,V>
是您真正想要的。
Do note that pretty much any time you write Map<K, List<V>>
or Map<K, Set<V>>
or some such, a ListMultimap<K, V>
or SetMultimap<K, V>
is what you really want.
这篇关于如何使用非唯一值与Guava进行地图反演?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!