Arp*_*sss 2 java bimap guava data-structures
在番石榴是否可能,
要BiMap对密钥值和多个值进行反向查找?确切地说,我有密钥和相应的多个值,我想从一个值获取密钥.
要存储多个值LinkedHashMap?确切地说,我想以某种顺序存储,键 - 多个值,因此我可以在列表中获得关键位置.
广告.1.是的,它可能做一个反向查找BiMap<K, V>,你刚才叫inverse你的BiMap,你会得到反转的BiMap<V, K> 观点你的BiMap.
示例(取自Guava的测试套件):
public void testMapConstructor() {
/* Test with non-empty Map. */
Map<String, String> map = ImmutableMap.of(
"canada", "dollar",
"chile", "peso",
"switzerland", "franc");
HashBiMap<String, String> bimap = HashBiMap.create(map);
assertEquals("dollar", bimap.get("canada"));
assertEquals("canada", bimap.inverse().get("dollar"));
}
Run Code Online (Sandbox Code Playgroud)
广告.2.假设你的意思是"我想存储,键 - >多个[集合]值"(Map<K, Collection<V>>),ListMultimap可能是你想要的,更精确ArrayListMultimap(保留值顺序)或LinkedListMultimap(保留键和值顺序).如果你的对象是不可变的,我强烈建议你使用ImmutableListMultimap.
您也可以Multimap使用factory(bit verbose)创建自己的实现,即我使用:
private static <K, V> ListMultimap<K, V> makeLinkedArrayListMultimap() {
return Multimaps.newListMultimap(Maps.<K, Collection<V>>newLinkedHashMap(),
new Supplier<List<V>>() {
@Override public List<V> get() {
return Lists.newArrayList();
}
});
}
public static void main(final String[] args) {
final ListMultimap<String, String> multimap = makeLinkedArrayListMultimap();
multimap.putAll("one", ImmutableList.of("zero", "three"));
multimap.putAll("two", ImmutableList.of("three", "four", "three"));
multimap.putAll("three", ImmutableList.<String>of()); // note that this doesn't add key to multimap
multimap.put("four", "forty-two");
System.out.println(multimap);
// prints {one=[one, three], two=[three, four, three], four=[forty-two]}
final List<String> listForOnes = multimap.get("one");
System.out.println(listForOnes.get(0));
// prints zero
}
Run Code Online (Sandbox Code Playgroud)
PS看看Guava的wiki,它解释了BiMap和Multimap.