Search code examples
javacomparatordigitslettersortedmap

Java SortMap Comparator to have digit keys ordered after letter keys


I need a SortedMap where the Charachter keys are sorted this way: ('A'..'Z'..'0'..'9'), so character first, then digits, all in ascending order. This is what I have tried so far, however, the output shows it fails in returning the sorting I want, because the values of the digit keys are still before the values of letter keys. What am I doing wrong? Is there an even better way to do this? Thanks in advance!

public static void main(String[] args) {
    SortedMap<Character, String> sortedMap = new TreeMap<>(new Comparator<Character>() {
        @Override
        public int compare(Character o1, Character o2) {
            if (Character.isDigit(o1) && Character.isLetter(o2)){
                return o2.compareTo(o1);
            }
            else if(Character.isLetter(o1) && Character.isDigit(o2)){
                return o1.compareTo(o2);
            }
            else{
                return o1.compareTo(o2);
            }
        }
    });

    sortedMap.put('5', "five");
    sortedMap.put('8', "nine");
    sortedMap.put('A', "ALPHA");
    sortedMap.put('G', "GOLF");
    sortedMap.put('F', "FOXTROT");
    System.out.println(sortedMap.values());
}

Solution

  • You need to return the result "o1 > o2" if o1 is a digit and o2 is a letter, so return 1 in this case. Similarly, if o1 is a letter and o2 is a digit, you need to return the result "o1 < o2", i.e. return -1.

    public int compare(Character o1, Character o2) {
       if (Character.isDigit(o1) && Character.isLetter(o2)){
          return 1;
       }
       else if(Character.isLetter(o1) && Character.isDigit(o2)){
          return -1;
       }
       else{
          return o1.compareTo(o2);
       }
    }