您的位置:首页 > 其它

对HashMap中的值进行排序

2016-04-13 20:56 399 查看
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);

map.put("A", 98.5);
map.put("B", 85.0);
map.put("C", 67.4);
map.put("D", 67.3);

System.out.println("unsorted map: " + map);

sorted_map.putAll(map);

System.out.println("results: " + sorted_map);
}


}

class ValueComparator implements Comparator {
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
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: