Friday, January 16, 2009

Bi-Directional Map : The values can be turned into the keys.

NOTE:
This example is a Hash Map on both the key and value. Notice that last-in wins. For example X kills C when D is put twice as the value.

The code:

BidiMap aMap = new DualHashBidiMap();
aMap.put("B", "A");
aMap.put("A", "B");
aMap.put("C", "D");
aMap.put("X", "D");
MapIterator it = aMap.mapIterator();
System.out.println("Before Inverse");
while (it.hasNext()) {
key = it.next();
value = it.getValue();
out.println(key + " -> " + value);
}
aMap = aMap.inverseBidiMap();
System.out.println("After Inverse");
it = aMap.mapIterator();
while (it.hasNext()) {
key = it.next();
value = it.getValue();
out.println(key + " -> " + value);
}

The results:

Before Inverse
A -> B
B -> A
X -> D
After Inverse
D -> X
A -> B
B -> A
Author: Philip A Senger

No comments:

Post a Comment