1

I have a map

Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(21,"A");
map.put(9,"B");
map.put(23,"C");
map.put(25,"D");

I sorted it like this

List<Integer> list = new LinkedList(map.keySet());
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
    return o1%10 - o2%10;
  }
});
Map sortedMap = new LinkedHashMap();
for(Integer key: list){
  sortedMap.put(key, map.get(key));
}
System.out.println(sortedMap);

Gives output {21=A, 23=C, 25=D, 9=B}

Even tried like this

Collections.sort(list);
Set set = map.entrySet();
Map result = new LinkedHashMap();
for (Iterator it = set.iterator(); it.hasNext();) {
    Map.Entry entry = (Map.Entry)it.next();
    result.put(entry.getKey(), entry.getValue());
}
System.out.println(result.toString());

Still same result

Why 9 is coming at last it must the first entry .

4
  • because 9 is biggest in ones place of all numbers !!! you are comparing last digit of all numbers... Commented Aug 25, 2014 at 12:33
  • Because you asked for it ! By explicitely stating % 10, you only keep the last digit of your numbers for the sort. :) Commented Aug 25, 2014 at 12:33
  • really this is stupidity how can I ignore that btw thanks for the help Commented Aug 25, 2014 at 12:38
  • The original map is already sorted. You only create a new ordered map that keeps the insertion order. What are you trying to achieve? Commented Aug 25, 2014 at 12:46

2 Answers 2

1

Your compare function is comparing only the last digit of each number:

@Override
public int compare(Integer o1, Integer o2) {
    return o1 % 10 - o2 % 10; // a number modulo 10 yields it last digit, e.g. 25 % 10 = 5
  }
});

You are comparing the last digits of (21, 9, 23, 24) which are (1, 9, 3, 4). In this way, 9 is the biggest number and hence the last one in the list.

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

Comments

1

Try this !

 List<Integer> list = new LinkedList(map.keySet());
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });

Is there any specific reason to use - % ? Which is changing the order of result.

This is the output with above

{9=B, 21=A, 23=C, 25=D}

Comments

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.