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;
       }    

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

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.