Bidirectional mapping using a single data structure

I came across some code recently at work (recreated to look like what I mean), similar to the code below

Is there a way I can recycle the code below to use a single data structure (taking into account performance)?

Here is some code to illustrate what I mean:

public class ObjectMapper { private Map<UUID,Integer> uuidMap; private Map<Integer,UUID> indexMap; public ObjectMapper(){ uuidMap = new HashMap<UUID,Integer>(); indexMap = new HashMap<Integer,UUID>(); } public void addMapping(int index, UUID uuid){ uuidMap.put(uuid, index); indexMap.put(index, uuid); } . . . public Integer getIndexByUUID(UUID uuid){ return uuidMap.get(uuid); } public UUID getUUIDByIndex(Integer index){ return indexMap.get(index); } } 
+4
source share
4 answers

This is answered here with a recommendation to use BiMap from the Google Collection

+5
source

Apache collections support the BidiMap interface and many fairly effective implementations.

+2
source

You can use one Map<Object,Object> for both mappings. Ugly, of course. Performance should be about the same or slightly better in the unlikely event that you have a lot of ObjectMapper with multiple values ​​displayed.

+1
source

You can use BiMap from the Eclipse Collection .

BiMap is a map that allows users to search in both directions. Both keys and values ​​in BiMap are unique.

The main implementation is HashBiMap .

inverse()

BiMap.inverse() returns a view in which the position of the key type and the type of value are reversed.

 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() behaves like Map.put() on a regular map, except that it issues when a duplicate value is added.

 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()

This behaves like MutableBiMap.put() , but it silently deletes the map entry with the same value before placing the key-value pair on the map.

 MutableBiMap<Integer, String> biMap = HashBiMap.newMap(); biMap.forcePut(1, "1"); // behaves like a regular put() biMap.forcePut(1, "1"); // no effect biMap.forcePut(1, "2"); // replaces the [1,"1"] pair with [1, "2"] biMap.put(2, "2"); // removes the [1, "2"] pair before putting Assert.assertFalse(biMap.containsKey(1)); Assert.assertEquals(HashBiMap.newWithKeysValues(2, "1"), biMap); 

Note. I am a committer for Eclipse collections.

+1
source

All Articles