Map集合按某個屬性排序
阿新 • • 發佈:2018-12-29
集合按照“xiangMuShu”這個屬性進行排序,示例程式碼如下:
List<TreeMap<String, Object>> listMap = new ArrayList<TreeMap<String,Object>>();
TreeMap<String, Object> map1 = new TreeMap<String, Object>();map1.put("xiangMuShu", 84.3);
map1.put("fenLeiName", "電子");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("xiangMuShu", 160.6);
map2.put("fenLeiName", "中醫藥");
TreeMap<String, Object> map3 = new TreeMap<String, Object>();
map3.put("xiangMuShu", 55.2);
map3.put("fenLeiName", "農林");
listMap.add(map1);
listMap.add(map2);
listMap.add(map3);
Collections.sort(listMap,new Comparator<TreeMap<String ,Object>>(){
@Override
public int compare(TreeMap<String, Object> o1, TreeMap<String, Object> o2) {
// TODO Auto-generated method stub
Double xiangMuShu = Double.parseDouble(o1.get("xiangMuShu").toString());
Double xiangMuShu2 = Double.parseDouble(o2.get("xiangMuShu").toString());
return xiangMuShu2.compareTo(xiangMuShu);
}}
);
for (TreeMap<String, Object> treeMap : listMap) {
System.out.println(treeMap.get("fenLeiName")+":"+treeMap.get("xiangMuShu"));
}