I am using Apache Commons Collections to create a MultiKeyMap that will store two keys with one corresponding value and then using MapIterator to walk through the map. The problem I've got is I need to break the keys returned by the MapIterator back into the individual keys rather than a single "composite". Whilst I could split the string containing the "composite" key or use reflections, neither of these options seem very elegant.
To model the problem, I've created the following sample code
MultiKeyMap multiKeyMap = new MultiKeyMap();
multiKeyMap.put("Key 1A","Key 1B","Value 1");
multiKeyMap.put("Key 2A","Key 2B","Value 2");
multiKeyMap.put("Key 3A","Key 3B","Value 3");
MapIterator it = multiKeyMap.mapIterator();
while (it.hasNext()) {
it.next();
System.out.println(it.getKey());
System.out.println(it.getValue());
}
it.getKey()
returns MultiKey[Key 3A, Key 3B] but what I want to do is assign the keys to individual variables, something like myKey1 = it.getKey().keys[0]
and myKey2 = it.getKey().keys[1]
but I cannot find anything in the JavaDoc to achieve this.
Is it possible break the keys returned by the MapIterator into the individual keys without using reflections or manipulating the string returned by it.getKey()?
I checked the source code for commons 3.2, and MultiKeyMap keys are instances of MultiKey, which has a getKey(int index) method. There is also a getKeys() method which returns Object[]. It requires a cast, but you could do:
MultiKeyMap multiKeyMap = new MultiKeyMap();
multiKeyMap.put("Key 1A","Key 1B","Value 1");
multiKeyMap.put("Key 2A","Key 2B","Value 2");
multiKeyMap.put("Key 3A","Key 3B","Value 3");
MapIterator it = multiKeyMap.mapIterator();
while (it.hasNext()) {
it.next();
MultiKey mk = (MultiKey) it.getKey();
// Option 1
System.out.println(mk.getKey(0));
System.out.println(mk.getKey(1));
// Option 2
for (Object subkey : mk.getKeys())
System.out.println(subkey);
System.out.println(it.getValue());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With