javacomparatortreemap

How to write a custom Comparator for TreeMap in Java?


I want to store key-value pairs in TreeMap and sort the entries based on the value of Key as per following logic:

Sort by the length of the key. If the length of two keys is same then sort them alphabetically. Example, for the following key-value pairs.

IBARAKI MitoCity
TOCHIGI UtunomiyaCity
GUNMA MaehashiCity
SAITAMA SaitamaCity
CHIBA ChibaCity
TOKYO Sinjyuku
KANAGAWA YokohamaCity

The expected output is like this.

CHIBA : ChibaCity
GUNMA : MaehashiCity
TOKYO : Sinjyuku
IBARAKI : MitoCity
SAITAMA : SaitamaCity
TOCHIGI : UtunomiyaCity
KANAGAWA : YokohamaCity

Solution

  • You need to write your own comparator for this and use it in TreeMap, e.g.:

    public class StringComparator implements Comparator<String> {
    
        @Override
        public int compare(String s1, String s2) {
            return s1.length() == s2.length() ? s1.compareTo(s2) : s1.length() - s2.length();
        }
    
        public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
            Map<String, String> map = new TreeMap<>(new StringComparator());
            map.put("IBARAKI", "MitoCity");
            map.put("TOCHIGI", "UtunomiyaCity");
            map.put("GUNMA", "MaehashiCity");
            map.put("SAITAMA", "SaitamaCity");
            map.put("CHIBA", "ChibaCity");
            map.put("TOKYO", "Sinjyuku");
            map.put("KANAGAWA", "YokohamaCity");
    
            System.out.println(map);
        }
    
    }
    

    This does not handle null values but you can add the handling if you are expecting null values in your use case.