I need a collection that can lookup a value based on the key and vice versa. For every value there is one key and for every key there is one value. Is there a ready to use d
You can use BiMap from Eclipse Collections (formerly GS Collections).
BiMap is a map that allows users to perform lookups from both directions. Both the keys and the values in a BiMap are unique.
The main implementation is HashBiMap.
inverse()
BiMap.inverse() returns a view where the position of the key type and value type are swapped.
MutableBiMap biMap =
HashBiMap.newWithKeysValues(1, "1", 2, "2", 3, "3");
MutableBiMap 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() behaves like Map.put() on a regular map, except it throws when a duplicate value is added.
MutableBiMap 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()
This behaves like MutableBiMap.put(), but it silently removes the map entry with the same value before putting the key-value pair in the map.
MutableBiMap 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);
Note: I am a committer for Eclipse Collections.