Reputation: 53
I want to sort my treemap by its value, I use a set> to do this, here is my code:
StringBuilder sb = new StringBuilder();
Map<Character, Integer> map = new TreeMap<>();
for (char c : s.toCharArray()){
map.put(c, map.getOrDefault(c, 0) + 1);
}
TreeSet<Map.Entry<Character, Integer>> set = new TreeSet<Map.Entry<Character, Integer>>(){
public int compare(Map.Entry<Character, Integer> e1, Map.Entry<Character, Integer> e2){
return e2.getValue() - e1.getValue();
}
};
for (Map.Entry<Character, Integer> e : map.entrySet()){
set.add(e);
}
// set.addAll(map.entrySet());
for (Map.Entry<Character, Integer> e : set){
for (int i = 0; i < e.getValue(); i++){
sb.append(e.getKey());
}
}
return sb.toString();
But I get the following error:
Exception in thread "main" java.lang.ClassCastException: java.util.TreeMap$Entry cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1251)
at java.util.TreeMap.put(TreeMap.java:495)
at java.util.TreeSet.add(TreeSet.java:212)
at Solution.frequencySort(Solution.java:14)
at __DriverSolution__.__helper__(__Driver__.java:4)
at __Driver__.main(__Driver__.java:48)
So why can't I add the entrySet to the treeSet?
Thanks!
Upvotes: 2
Views: 107
Reputation: 29680
Because Map.Entry
does not implement Comparable
. You're also not providing a Comparator
for the TreeSet
, even though you may think you already are.
With Java 10, you can use the following:
var set = new TreeSet<>(Comparator.<Map.Entry<Character, Integer>, Integer>comparing(Map.Entry::getValue).reversed());
Upvotes: 2