我想按照其值对树形图进行排序,我使用一组>要做到这一点,这是我的代码:
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();
但是我收到以下错误:
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)
那为什么我不能将entrySet添加到treeSet?
谢谢!
答案 0 :(得分:2)
因为Map.Entry
未实现Comparable
。您还没有为Comparator
提供TreeSet
,即使您可能认为自己已经是var set = new TreeSet<>(Comparator.<Map.Entry<Character, Integer>, Integer>comparing(Map.Entry::getValue).reversed());
。
使用Java 10,您可以使用以下内容:
number = input("Enter a whole number in the range of 1-99: ")
for i in range(int(number), 100, int(number)):
print(i, end = ", ")