Sorting Descending order: Java Map

前端 未结 5 1862
不思量自难忘°
不思量自难忘° 2020-12-05 04:28

What I want to do is sort a map by value. I went over many questions that are available on the stackoverflow site and found out following solution that does what I want but

5条回答
  •  自闭症患者
    2020-12-05 04:58

    To change the solution in the link to sort by descending order, just reverse the condition:

    ...
    // Note: this comparator imposes orderings that are inconsistent with equals.    
    public int compare(String a, String b) {
        if (base.get(a) >= base.get(b)) {
            return 1; // For ascending, return -1;
        } else {
            return -1; // For ascending, return 1;
        } // returning 0 would merge keys
    }
    ...
    

提交回复
热议问题