Java-如何对TreeMap进行排序

我的代码提示用户输入0到100之间的数字,然后计算每个数字出现多少次。

我正在尝试通过以下方式对TreeMap进行排序:

Output

This is my code below, and currently, the output is unsorted. I've tried implementing the method from this link, https://beginnersbook.com/2014/07/how-to-sort-a-treemap-by-value-in-java/, but got the following error:

原因:无法推断类型变量K,V (参数不匹配; ArrayList无法转换为Map) 其中K,V是类型变量: K扩展在方法sortByValues(Map)中声明的Object V扩展在方法sortByValues(Map)中声明的Comparable

有什么建议?

public static void main(String[] args){
    Scanner input = new Scanner(System.in);

    ArrayList<Integer> Digits = new ArrayList<>();
    ArrayList<Integer> UniqueDigits = new ArrayList<>();
    System.out.print("Enter digits: ");
    int value;

    do {
        value = input.nextInt();
        if (value > 0 && value < 101) 
            Digits.add(value);
        } while (value != 0);


    Set<Integer> uniqueDigits = new HashSet<Integer>(Digits);
    Map<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
    for (Integer uniqueDigit : uniqueDigits) {
        frequencies.put(uniqueDigit, Collections.frequency(Digits, uniqueDigit));
    }


    // Printing
    for (Integer key : frequencies.keySet()) {

        if (frequencies.get(key) > 1) {
            System.out.println(key + " - " + frequencies.get(key) + " times");
            } else if (frequencies.get(key) == 1) {
            System.out.println(key + " - " + frequencies.get(key) + " time");
            }
    }
}

}

评论