Sorting HashMap by value using a TreeMap and Comparator

前端 未结 3 601
离开以前
离开以前 2021-01-29 00:48

Im using the following code to create a hashmap and then sort the values in the hashmap by using a treemap and a comparator. However, the output is rather unexpected. So any th

3条回答
  •  时光说笑
    2021-01-29 01:36

    Please check the JavaDoc of compare: You do not return the bigger value, but -1 for o1 < o2, 0 for o1 = o2 and 1 for o1 > o2. So you could write:

    @Override
    public int compare(Object o1, Object o2) {
        return ((Integer) map.get(o1)).compareTo((Integer) map.get(o2);
    }
    

提交回复
热议问题