tags:

views:

70

answers:

3

I need to do a search in a map of maps and return the keys this element belong. I think this implementation is very slow, can you help me to optimize it?. I need to use TreeSet and I can't use contains because they use compareTo, and equals/compareTo pair are implemented in an incompatible way and I can't change that. (sorry my bad english)

Map<Key, Map<SubKey, Set<Element>>> m = new TreeSet();

public String getKeys(Element element) { 
 for(Entry<Key, Map<SubKey, Set<Element>>> e : m.entrySet()) {
  mapSubKey = e.getValue();
  for(Entry<SubKey, Set<Element>> e2 : mapSubKey.entrySet()) {
   setElements = e2.getValue();
   for(Element elem : setElements)
    if(elem.equals(element)) return "Key: " + e.getKey() + " SubKey: " + e2.getKey();
  }
 }
}
A: 

if you can't use contains, and you're stuck using a Map of Maps, then your only real option is to iterate, as you are doing.

alternatively, you could keep a reverse map of Element to Key/SubKey in a separate map, which would make reverse lookups faster.

also, if you're not sure that a given Element can exist in only one place, you might want to store and retrieve a List<Element> instead of just an Element

oedo
It's a problem?/practice? for the University, and I'm stuck with prerequisites, so keeping a reverse map is not an option. Element only exists in one place. Thank you for the answer.
Kronen
In java elements ALWAYS only exist in one place, however multiple collections can contain references to the same object. Generally to do this kind of thing I would implement my own collection that wraps all the functionality you need--that way you may have two collections inside doing the work, but your collection is the only one users would see. This also makes changes much easier later when they change the requirements on you.
Bill K
A: 

Using TreeMap and TreeSet work properly when compareTo and equals are implemented in such a way that they are compatible with each other. Furthermore, when searching in a Map, only the search for the key will be efficient (for a TreeMap O(log n)). When searching for a value in a Map, the complexity will become linear.

There is a way to optimize the search in the inner TreeSet though, when implementing your own Comparator for the Element type. This way you can implement your own compareTo method without changing the Element object itself.

Marc
I don't understand you, I have compareTo (Comparable) and compare (Comparator) methods implemented for Element, but they are implemented in a way incompatible with equals(this is a prerequisite), so I have to check before adding if there is an equal element in the treeset already. Thank you for your answer.
Kronen
+4  A: 
erickson
I can only use standard Java Collections and keeping a reverse map is not an option. So I think this is the only way of doing this with those prerequisites, so I'll need to optimize in another part.Thank you for your answer.
Kronen