3

I have created a map called result.

In the sortByKeys method as my keys are String with Numeric values, I have converted them to Integer key type Map then sorted them.

The sorting is working fine when I am looping and printing individually, but not when I am setting them in another Map.

public class TestDate {
    public static void main (String args[]){

    Map<String, String> result = new HashMap<String, String>();

        result.put("error", "10");
        result.put("1","hii");
        result.put("Update","herii");
        result.put("insert","insert");
        result.put("10","hiiuu");
        result.put("7","hii");
        result.put("21","hii");
        result.put("15","hii"); 

        Map<String, String> sorted = sortByKeys(result);
        //System.out.println(sorted);   
    }

    private static Map<String, String> sortByKeys(Map<String, String> map) {
        Map <Integer,String> unSorted = new  HashMap<Integer, String>();
        Map <String,String> sorted = new  HashMap<String, String>();
        for (Map.Entry<String, String> entry : map.entrySet())
        {
            try{
                int foo = Integer.parseInt(entry.getKey());            
                unSorted.put(foo, entry.getValue());                
            }catch (Exception e){

            }
        }
        Map<Integer, String> newMap = new TreeMap<Integer, String>(unSorted); 
        Set set = newMap.entrySet();
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            Map.Entry me = (Map.Entry)iterator.next();
            System.out.println(me.getKey());
            System.out.println(me.getValue());
            sorted.put(me.getKey().toString(),  me.getValue().toString());

       }
        System.out.println(sorted);

        return null;
    }   
}

Here is the o/p :

1
hii
7
hii
10
hiiuu
15
hii
21
hii
{21=hii, 10=hiiuu, 1=hii, 7=hii, 15=hii}

3 Answers 3

8

If you don't need the last inch of performance, you can solve this rather directly, without an extra step to sort the map, by using SortedMap:

Map<String,String> result = new TreeMap<>(Comparator.comparingInt(Integer::parseInt));

If you are among the unfortunate bunch who are still being denied access to Java 8, you'll have to implement the Comparator in long-hand:

new TreeMap<>(new Comparator<String,String> { public int compare(String a, String b) {
  return Integer.compare(Integer.parseInt(a), Integer.parseInt(b));
}});

The above approach works only under the assumption that all keys are parseable integers. If that is not the case, then you won't be able to use the SortedMap directly, but transform your original map into it, filtering out the unparseable keys.

Sign up to request clarification or add additional context in comments.

10 Comments

I am not sure how to use it .
You just put your stuff into it, and when you want the sorted keys, just use result.keySet() and it will be in order.
Ok , But i am getting an error here Integer::parseInt , Integer cannot be resolved to a variable .
You are not on Java 8, then. In that case you cannot use the method reference and need to write out the full implementation of Comparator as an anonymous class instance.
But OP is putting in some non-integer Strings as keys (into result, though not into the second Map he was creating). Surely this will give exceptions in the Comparator when it tries to call Integer.parseInt() on something that isn't parseable?
|
2

It's because the Map you're putting them into is a HashMap, which isn't sorted. There's no guarantee of the ordering of results you'll get out of the HashMap, even if you put them in in the right order.

(And calling it sorted doesn't change anything :) )

Comments

1

You print 2 different maps and not the same: you iterate over and print the entries of newMap map, and at the end you print sorted map.

You see the sorted entries printed because you iterate over your sorted newMap.

Then you print the sorted map which is unsorted (despite by its name). You print a different map instance.

Print this:

System.out.println(newMap); // This is the instance of the sorted "TreeMap"

3 Comments

Yes that is working . But I want the sorted Map (newMap) in <String,String> format . Which is now <Integer,String> . So I tried to loop through .
But sorted is a HashMap which is not even sorted, but even if you would use TreeMap<String, String> it cannot do what you want because the lexicographical order of Strings is different from the natural order of numbers even if the Strings contain numbers: "2" is greater than "11" even though 2 is less than 11.
Yes I can see the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.