[英]Java Collection - Unique Key and Unique Value
我需要一個可以根據鍵查找值的集合,反之亦然。 每個值都有一個鍵,每個鍵都有一個值。 是否有現成的數據結構可以做到這一點?
來自Google Guava的BiMap看起來很適合你。
雙映射(或“雙向映射”)是一種保留其值及其鍵的唯一性的映射。 此約束使 bimap 能夠支持“反向視圖”,這是另一個 bimap,包含與此 bimap 相同的條目,但具有相反的鍵和值。
或者來自Apache Commons Collections的BidiMap :
定義允許在鍵和值之間進行雙向查找的映射。
這個擴展的
Map
表示一個映射,其中一個鍵可以查找一個值,一個值可以同樣輕松地查找一個鍵。 該接口擴展了Map
,因此可以在需要地圖的任何地方使用。 該界面提供了反向地圖視圖,可以完全訪問BidiMap
兩個方向。
您可以使用Eclipse Collections (以前稱為 GS Collections)中的BiMap 。
BiMap
是一種允許用戶從兩個方向執行查找的地圖。 BiMap 中的鍵和值都是唯一的。
主要實現是HashBiMap
。
inverse()
BiMap.inverse()
返回一個視圖,其中鍵類型和值類型的位置被交換。
MutableBiMap<Integer, String> biMap =
HashBiMap.newWithKeysValues(1, "1", 2, "2", 3, "3");
MutableBiMap<String, Integer> inverse = biMap.inverse();
Assert.assertEquals("1", biMap.get(1));
Assert.assertEquals(1, inverse.get("1"));
Assert.assertTrue(inverse.containsKey("3"));
Assert.assertEquals(2, inverse.put("2", 4));
put()
MutableBiMap.put()
表現得如同Map.put()
常規地圖上,除了當添加一個重復的值被它拋出。
MutableBiMap<Integer, String> biMap = HashBiMap.newMap();
biMap.put(1, "1"); // behaves like a regular put()
biMap.put(1, "1"); // no effect
biMap.put(2, "1"); // throws IllegalArgumentException
forcePut()
它的行為類似於MutableBiMap.put()
,但它會在將鍵值對放入映射之前默默地刪除具有相同值的映射條目。
MutableBiMap<Integer, String> biMap = HashBiMap.newMap();
biMap.forcePut(1, "1"); // behaves like a regular put()
biMap.forcePut(1, "1"); // no effect
biMap.put(1, "2"); // replaces the [1,"1"] pair with [1, "2"]
biMap.forcePut(2, "2"); // removes the [1, "2"] pair before putting
Assert.assertFalse(biMap.containsKey(1));
Assert.assertEquals(HashBiMap.newWithKeysValues(2, "2"), biMap);
注意:我是 Eclipse Collections 的提交者。
接受的答案提到了BiMap
,但它與谷歌番石榴庫變得更加最新。
BiMap<K, V>
是Map<K, V>
- 允許您使用
inverse()
查看“反向”BiMap<V, K>
- 確保值是唯一的,使
values()
成為一個Set
所以,你可以得到這樣的代碼:
final BiMap<String, Integer> biMap = HashBiMap.create();
biMap.put("word", 1);
biMap.put("alpha", 2);
System.out.println(biMap.get("word")); // prints 1
System.out.println(biMap.inverse().get(1)); // prints word
這個對象的一些注意事項:
IllegalArgumentException
。 您可以使用forcePut(key, value)
,但這將覆蓋現有的鍵值對。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.