java中根据map的value进行排序
PHPz
PHPz 2017-04-18 10:31:50
0
2
468

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
    }
}
PHPz
PHPz

学习是最好的投资!

reply all(2)
大家讲道理

When sorted_map is initialized, you give it a Comparator, so when sorted_map.putAll(map), you actually put each entry in the map into sorted_map. Every time you put one, sorted_map will call the compare method of Comparator. Let's compare and decide where to put it, so that the entries of sorted_map are arranged according to the order rules of Comparator.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template