I am looking for a data structure such as a bidirectional map that allows to map from a unique key to it's unique value and also from its value to the key.
I found this example of a BidiMap
public class IdToNames {
public static void main(String[] args){
BidiMap<String, Integer> map = new DualHashBidiMap<>();
map.put("NameA", 100);
map.put("NameB", 200);
System.out.println(map.size()); //2 as expected
System.out.println(map.get("NameA")); //100 as expected
System.out.println(map.getKey(100)); //"NameA" as expected
}
}
So far, so good. That was what I was looking for. But if one puts a new entry into the map, which contains already existing keys and or values, old entries are thrown away in order to keep the new entry while still having unique keys and unique values.
public class IdToNames {
public static void main(String[] args){
BidiMap<String, Integer> map = new DualHashBidiMap<>();
map.put("NameA", 100);
System.out.println(map.size()); //1 as expected
map.put("NameB", 200);
System.out.println(map.size()); //2 as expected
map.put("NameA", 200); // unfortunately this works without warnings
System.out.println(map.size()); //1 which is problematic
System.out.println(map.get("NameA")); //now 200
System.out.println(map.getKey(100)); //null
}
}
Is there a good way to prevent silently altering the map. I would prefer a data structure that rejects new entries which would violate uniqueness of existing keys or values. Any ideas are welcome.