Hi all,

I actually need to use a sorted map.So i tried using Tree Map.But the problem is that This works well with sort key having values upto 9. With more than 10 items I see abrupt results with sort key arranged in the order = 1, 10, 11,12,--------17, 2, 3, 4, 5, 6, 7, 8, 9. I even tried using Comparator for this ....But the same way it is sorted...How to make it arrange in the correct order of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11?

Please find my code below

public static TreeMap sortByComparator(TreeMap unsortMap) {

            List list = new LinkedList(unsortMap.entrySet());
            System.out.println("the list value is "+list);

            //sort list based on comparator
        Collections.sort(list, new Comparator() {
              public int compare(Object o1, Object o2) {
                   return ((Comparable) ((Map.Entry) (o2)).getKey())
                   .compareTo(((Map.Entry) (o1)).getKey());

            //put sorted list into map again
        TreeMap sortedMap = new TreeMap();
        for (Iterator it = list.iterator(); it.hasNext();) {
             Map.Entry entry = (Map.Entry)it.next();
             sortedMap.put(entry.getKey(), entry.getValue());
        return sortedMap;
4 Years
Discussion Span
Last Post by JamesCherrill

That looks like your keys are Strings. In the Comparator you could parse them into integers and compare those values.

Votes + Comments
But how to use an integer iterator????There are lots of integer keys from 1-17 in this treemap

You don't need an integer iterator. Just in your comparator instead of comparing the raw Strings, convert each String to aan int and compare those. Then a sort using that comparator will sort inh the order you wanted.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.