Search code examples
javasortingcomparecomparatortreemap

How to override comparator for TreeMap


I am currently implementing a TreeMap to store key-value pairs, where the key is a regular String and the value is a stack of objects. From what I understand (this is my first time using a Map so I am very green), the TreeMap class uses the natural order of keys to sort itself, however I would like for it to be sorted Lexicographically. Again from what I understand, its comparator method can be overwritten to accomplish this. I already have an idea of how I will make it lexicographic, my issue lies in the fact that I don't know how to actually override the method. Do I put the overridden part in the in the class I am using the TreeMap? do I have to make a separate class called tree map and write the new method there? What is the special syntax (if any) for overriding a compare method? I am sorry if this question seems basic, but I am very new at this and looking online I have struggled to find an explanation that I fully understand. Thank you in advance for your help and patience!


Solution

  • Try this as an example:

    class SortAscendingComparator implements Comparator<String> {
      @Override
      public int compare(String s1, String s2) {
        return s1.compareTo(s2);
      }
    }
    
    public class Demo {
      public static void main(String[] args) {
        SortedMap<String, String> map = new TreeMap<>(new SortAscendingComparator());
        map.put("c", "c");
        map.put("a", "a");
        map.put("b", "b");
        // Displays: {a=a, b=b, c=c}
        System.out.println(map);
      }
    }