• Post Reply Bookmark Topic Watch Topic
  • New Topic

Resort a treeMap  RSS feed

 
Lester Tam
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I would like to know if there are convenient ways to resort a treeMap, there is my failed testing code:
////////////////////////////////////////////////////////////
import java.util.TreeMap;
public class SortedKey implements Comparable {
public static Object sortType = "name";
public String key;
public String name;
public String type;
public static void main(String[] args) {
TreeMap tm = new TreeMap();
tm.put(new SortedKey("k1", "T", "C"), "1");
tm.put(new SortedKey("k2", "A", "D"), "2");
tm.put(new SortedKey("k3", "H", "Z"), "3");
tm.put(new SortedKey("k4", "Z", "A"), "4");
//try re-sort ! //
SortedKey.sortType = "name";
System.out.println(tm.entrySet()); //our=[k1=1, k2=2, k3=3, k4=4]
SortedKey.sortType = "key";
System.out.println(tm.entrySet()); //our=[k1=1, k2=2, k3=3, k4=4]
SortedKey.sortType = "type";
System.out.println(tm.entrySet()); //our=[k1=1, k2=2, k3=3, k4=4]
// ---------- //
}
public int compareTo(Object arg0) {
SortedKey tmp = (SortedKey) arg0;
if (sortType.toString() == "key")
return (this.key.compareTo(tmp.key));
else if (sortType.toString() == "name")
return (this.name.compareTo(tmp.name));
else
return (this.type.compareTo(tmp.type));
}
public SortedKey(String name, String key, String type) {
this.name = name;
this.key = key;
this.type = type;
}
public String toString() {
return name;
}
}
////////////////////////////////////////////////////////////
any idea ?
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to The Intermediate Forum...
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, there's no way to do this that I know of. But if there were, it would necessarily be no cheaper than creating a new map and simply adding all the pairings -- i.e.,
 
Lester Tam
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!