0

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!

abdcg
  • 137
  • 1
  • 11

3 Answers3

2

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);
  }
}
geffchang
  • 3,279
  • 2
  • 32
  • 58
  • Ok, so the idea would be to define the new comparator in a class of its own, then when I call the actual Tree Map, I would call on that class between the brackets? Also, very quickly, something I noticed while comparing your code to mine was that you initialized the TreeMap using "SortedMap map = new TreeMap<>(new SortAscendingComparator())", whereas with my code i wrote "TreeMap> map = new TreeMap<>()". Does initializing the TreeMap with SortedMap make a difference? – abdcg Apr 25 '20 at 18:03
  • 1
    @abdcg `TreeMap map = new TreeMap<>(new SortAscendingComparator());` is also OK. `SortedMap` is an interface that `TreeMap` implements. – geffchang Apr 25 '20 at 18:16
1

TreeMap class has specific constructor that accepts custom Comparator object. You can put your logic inside passed comparator.

Vasily Liaskovsky
  • 2,248
  • 1
  • 17
  • 32
1

Actually, you can pass a Comparator instance of your own to one of the TreeMap's constructors. Using lambda expression, you can even simplify it to:

TreeMap<String, String> t = new TreeMap<>(String::compareTo);