Reverse a TreeMap

Hi, Would you please to teach me how I can reverse a TreeMap ?Best regards,Eric
[114 byte] By [EricMacau] at [2007-9-26 1:17:03]
# 1

Write a Comparator that wraps the ACTUAL Comparator and implements a "flip" method, that simply swaps the sign of the result of the compare(Object, Object) method of the underlying Comparator in a new Object.

Then make a new TreeMap with the contents of the initial TreeMap and the new Comparator. I don't know what would happen if you started to mess around with the Comparator that was being used by a TreeMap - I guess it would be OK as long as you made sure (ie. synchronized) that nothing was iterating over it at the same time.

public class FlippableCompWrapper implements Comparator {

private flip = 1;

private Comparator realComp;

public FlippableCompWrapper(Comparator c, int flip) {

this.flip = flip;

realComp = c;

}

public void flip() {

return new FlippableCompWrapper(c, -1);

}

public int compare(Object o1, Object o2) {

return flip*realComp.compare(o1, o2);

}

public void equals(Object o) { return this == o; }

}

oxbow_lakes at 2007-6-29 0:45:53 > top of Java-index,Core,Core APIs...
# 2

It depends on what you mean by reverse.

If you want all values in a name/value pair to be stored as names with the old name as the value, do the following. However, be aware that each name is unique (if more than one name/value pair has the same value, building a Map by value will have only 1 entry corresponding to the name).

TreeMap tm; // create and fill

TreeMap reverse_tm = new TreeMap();

Set set = tm.entrySet();

Iterator iterator = set.iterator();

while( iterator.hasNext() ) {

Map.Entry entry = (Map.Entry)iterator.next();

reverse_tm.put(entry.getValue(), entry.getKey()); // getValue() will overwrite

}

If you want to view the TreeMap in reverse, just count down from the end

TreeMap tm; // create and fill

Object[] setobjs = tm.keySet().toArray();

for(int i=setobjs.length; i>=0; i--) {

System.out.println(setobjs[i] + "/" +tm.get(setobjs[i]));

}

CWalker807 at 2007-6-29 0:45:53 > top of Java-index,Core,Core APIs...