Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

how to sort a Map

800965Feb 17 2011 — edited Feb 17 2011
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
This post has been answered by YoungWinston on Feb 17 2011
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 17 2011
Added on Feb 17 2011
5 comments
167 views