In Java, sort hash map by its key.length()
The compiler is complaining because you cannot call compareTo
on an int
. The correct way to sort the map is the following:
Map<String, Integer> treeMap = new TreeMap<String, Integer>(
new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
if (s1.length() > s2.length()) {
return -1;
} else if (s1.length() < s2.length()) {
return 1;
} else {
return s1.compareTo(s2);
}
}
});
The first two conditions compare the lengths of the two String
s and return a positive or a negative number accordingly. The third condition would compare the String
s lexicographically if their lengths are equal.
You call String#length()
, which returns a primitive int
. You need the static method Integer.compare(int,int)
. If you are on Java 8, you can save yourself a lot of typing:
Map<String,Integer> treeMap = new TreeMap<>(
Comparator.comparingInt(String::length)
.thenComparing(Function.identity()));
public int compare(String o1, String o2) {
return o1.length() == o2.length() ? o1.compareTo(o2) : o1.length() - o2.length();
}