I have a treemap with some strings and the frequencies of those strings.
I want to sort based on the frequencies, therefore I decided to write a custom comparator.
What is wrong with this piece of code? It throws an exception.
TreeMap<String, Integer> map = new TreeMap(new Comparator<Map.Entry<String, Integer>>(){
public int compare(Map.Entry<String, Integer> m1, Map.Entry<String, Integer> m2) {
return m2.getValue() - m1.getValue();
}
});
Exception
java.lang.ClassCastException: class java.lang.String cannot be cast to class java.util.Map$Entry (java.lang.String and java.util.Map$Entry are in module java.base of loader 'bootstrap')
2
You are using the wrong type for the Comparator. The constructor is as follows:
public TreeMap(Comparator<? super K> comparator)
where K
is the type of the Map
‘s key.
That means you need to pass a Comparator<String>
to the constructor.
You want to sort the Map
using the values, that’s not possible using the constructor. You will need to sort the entries manually with entrySet()
and the Comparator you are currently using.
1
The TreeMap
in Java is specifically designed to sort its entries based on the keys, not the values. The comparator you provide to a TreeMap
is only used to compare the keys. If you try to use a comparator that expects a different type (e.g., Map.Entry<String, Integer>
), the TreeMap
will attempt to cast the key to that type. This will result in a ClassCastException
, such as java.lang.String cannot be cast to java.util.Map$Entry
, because the keys are not of the expected type.