Hi guys,
I'm doing an exercise. I want to get a TreeMap sorted by keys and print it out. I thought I can just assign a HashMap instance to a TreeMap instance and it will be sorted automatically, but it doesn't work. This is the code:
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("One", "1");
map.put("Two", "2");
map.put("Three", "3");
map.put("Four", "4");
map.put("Five", "5");
System.out.println(map);
Map<String, String> treeMap = new TreeMap<String, String>();
treeMap = map;
System.out.println(treeMap);
}
}
And this is the output:
{Five=5, Three=3, One=1, Four=4, Two=2}
{Five=5, Three=3, One=1, Four=4, Two=2}
How can I sort a TreeMap or a HasMap object? So far I only found Collections.sort() but it works only for a List.
Thanks,
PR.
Edited by: Aardenon on Feb 17, 2011 1:21 PM
Edited by: Aardenon on Feb 17, 2011 1:22 PM