搜尋

首頁  >  問答  >  主體

java中根据map的value进行排序

public class Testing {

    public static void main(String[] args) {
        HashMap<String,Double> map = new HashMap<String,Double>();
        ValueComparator bvc =  new ValueComparator(map);
        TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);
        sorted_map.putAll(map);
    }
}
class ValueComparator implements Comparator<String> {
    Map<String, Double> base;
    public ValueComparator(Map<String, Double> base) {
        this.base = base;
    }
    // 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;
        } else {
            return 1;
        } // returning 0 would merge keys
    }
}
PHPzPHPz2919 天前471

全部回覆(2)我來回復

  • 大家讲道理

    大家讲道理2017-04-18 10:33:50

    sorted_map在初始化的時候,你給了它Comparator, 所以sorted_map.putAll(map)的時候,其實就是把map裡的每個entry放進sorted_map裡,每放一個,sorted_map就會呼叫Comparator的compare方法來比較一下,決定放在哪個位置,這樣sorted_map的entry就都是依照Comparator的順序規則來排列的啦。

    回覆
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:33:50

    回覆
    0
  • 取消回覆