• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Resort a treeMap

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Moving this to The Intermediate Forum...
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks
reply
    Bookmark Topic Watch Topic
  • New Topic