Issue
I have a java TreeMap<String, Integer> (let's call it multiset for now, because that is what I am using it for), and I want it to be sorted by the string's length. What I mean is that for some code like this:
// Imports
import java.util.Comparator;
import java.util.TreeMap;
class CompareLength implements Comparator<String> {
public int compare(String string, String string_2) {
return Integer.compare(string.length(), string_2.length());
}
}
// More lines of code ...
TreeMap<String, Integer> multiset = new TreeMap<>(new CompareLength());
multiset.put("abc", 1);
multiset.put("x", 1);
multiset.put("yz", 1);
for (String string: multiset.keySet()) {
System.out.print(string + " ");
}
System.out.println(multiset.containsKey("xyz") + " ");
The output is: x yz abc true
I wanted it to be sorted by length, not completely change the comparator of the TreeMap! How do I do this? I also want this to work no matter what the comparator is, the key type, the keys, the value, the value type, etc.
Solution
As you realized, the Comparator
passed to a TreeMap
doesn't just specify the order of the entries, but also which entries are considered equivalent (i.e. those for which Comparator.compare()
returns 0).
The conclusion is that you simply shouldn't return 0 for any two string values, unless they are indeed identical. A simple way is to use a Comparator like this:
class CompareLength implements Comparator<String> {
public int compare(String str1, String str2) {
int result = Integer.compare(str1.legnth(), str2.length());
if (result == 0) {
result = str1.compareTo(str2);
}
return result;
}
}
Answered By - Joachim Sauer
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)