1. 程式人生 > 其它 >JAVA中對List<map<String,Object>>根據map某個key值從小到大順序進行排序

JAVA中對List<map<String,Object>>根據map某個key值從小到大順序進行排序

 

public static void main(String[] args)  {
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    Map<String, Object> map1 = new HashMap<String, Object>();
    map1.put("name", "p");
    map1.put("周", "10");
    Map<String, Object> map2 = new
HashMap<String, Object>(); map2.put("name", "h"); map2.put("周", "11"); Map<String, Object> map3 = new HashMap<String, Object>(); map3.put("name", "f"); map3.put("周", "12"); Map<String, Object> map4 = new HashMap<String, Object>(); map4.put("name", "f"); map4.put(
"周", "9"); Map<String, Object> map5 = new HashMap<String, Object>(); map5.put("name", "f"); map5.put("周", "8"); list.add(map1); list.add(map3); list.add(map2); list.add(map4); list.add(map5); Collections.sort(list, new Comparator<Map<String, Object>>() {
public int compare(Map<String, Object> o1, Map<String, Object> o2) { Integer name1 = Integer.valueOf(o1.get("周").toString()) ;//name1是從你list裡面拿出來的一個 Integer name2 = Integer.valueOf(o2.get("周").toString()) ; //name1是從你list裡面拿出來的第二個name return name1.compareTo(name2); } }); }

輸出的結果: