Home > Mobile >  Java TreeMap : Unable to sort the TreeMap key in decreasing order of the length/value
Java TreeMap : Unable to sort the TreeMap key in decreasing order of the length/value

Time:12-09

I am trying to use the TreeMap to sort my keys, which are being stored in the Map<String,Integer>. But for some reason, the keys are not arranged correctly in decreasing order, as intended. I would like to know if there is a default way to achieve the intended order of the keys or I need to write some custom method to achieve this?

Following is the sample code I have:

public class ApplicationMain {
    public static void main(String[] args) {
        final Map<String, Integer> sampleTreeMap = new TreeMap<>();
        sampleTreeMap.put("5903766131", 6);
        sampleTreeMap.put("5903767", 7);
        sampleTreeMap.put("590376614", 5);
        sampleTreeMap.put("5903766170", 9);
        sampleTreeMap.put("59037662", 12);
        sampleTreeMap.put("5903766410", 10);

        sampleTreeMap.entrySet().stream().forEach(entry ->{
            System.out.println("Key : "   entry.getKey()   " -- "   entry.getValue());
        });
    }
}

The following is the output I am getting:

Key : 5903766131 -- 6
Key : 590376614 -- 5
Key : 5903766170 -- 9
Key : 59037662 -- 12
Key : 5903766410 -- 10
Key : 5903767 -- 7

I would like the output to be in descending order of the keys, so a larger number with a higher number of digits or characters would appear at the top, then a lower number with fewer digits. Something like this:

Key : 5903766410 -- 10
Key : 5903766170 -- 9
Key : 5903766131 -- 6
Key : 590376614 -- 5
Key : 59037662 -- 12
Key : 5903767 -- 7

Note:

  1. I cannot change my data type to Integer or Long as this is coming from another application, and I would like to use it as a string in further processing, so I would like to find a way in which I can sort them properly.

  2. I was previously using HashMap, but after discovering that it does not support ordering, I switched to TreeMap.

Please provide some suggestions on how to fix the issue.

CodePudding user response:

It looks like you want to sort the keys as numbers instead of strings. One way to do this is to provide a custom Сomparator when creating the map.

final Map<String, Integer> sampleTreeMap =
                new TreeMap<>((Comparator.comparingLong((String s) -> Long.parseLong(s))).reversed());

P.S. You might find it helpful to read this question Comparator .comparing().reversed() strange behaviour / not working as expected

  • Related