0

How correctly to implement the Comparator for the Treemap? It should: 1. Sort words by the length of the line in descending order. 2. Words of equal length sort alphabetically.

class Test implements Comparator<String> {

    public static SortedMap<String, String> doSort(String str) {
        Comparator<String> comparator = new Test();
        SortedMap<String, String> map = new TreeMap<>(comparator);

        //do something to input String

        return map;
    }


    @Override
    public int compare(String o1, String o2)
    {
        return o2.length() - o1.length();
    }
}

is that enough? How to add alphabet sorting in the second turn?

naut92
  • 103
  • 1
  • 13
  • 1
    Possible duplicate of [How to compare objects by multiple fields](https://stackoverflow.com/questions/369512/how-to-compare-objects-by-multiple-fields) – Joe C Aug 05 '17 at 20:58
  • I don't need several fields. I need 2 methods of sorting: 1.Length. 2.Alphabet. – naut92 Aug 06 '17 at 01:00

1 Answers1

3

Assuming you are using Java 8+, you could write this with a lambda such as

Comparator<String> comparator = (a,b) -> {
    int r = Integer.compare(a.length(), b.length());
    if (r != 0) {
        return r;
    }
    return a.compareTo(b);
};

In Java 7 and earlier, it might do

Comparator<String> comparator = new Comparator<String>() {
    public int compare(String a, String b) {
        int r = Integer.compare(a.length(), b.length());
        if (r != 0) {
            return r;
        }
        return a.compareTo(b);
    }
};
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • So sorry, I don't see 2 sorting, only 1: the length of the word. I need two: 1.The length of the word. 2.Alphabet. Or does it mean that Treemap itself sorts the comparison string length? Unfortunately, in my case it doesn't work. – naut92 Aug 06 '17 at 01:07
  • 1
    The `return a.compareTo(b);` when `r == 0` is comparing alphabetically. This is exactly what you asked for. – Elliott Frisch Aug 06 '17 at 01:08