JAVA中對List<map<String,Object>>根據map某個key值從小到大順序進行排序
阿新 • • 發佈:2018-11-27
/** * @功能描述:排序方法 * @author LJ * 2018年10月29日 -下午2:38:15 */ public class java_ListMapSort { 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("cj", "15"); Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("name", "h"); map2.put("cj", "2"); Map<String, Object> map3 = new HashMap<String, Object>(); map3.put("name", "f"); map3.put("cj", "21"); list.add(map1); list.add(map3); list.add(map2); //排序前 for (Map<String, Object> map : list) { System.out.println(map.get("cj")); } 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("cj").toString()) ;//name1是從你list裡面拿出來的一個 Integer name2 = Integer.valueOf(o2.get("cj").toString()) ; //name1是從你list裡面拿出來的第二個name return name1.compareTo(name2); } }); //排序後 System.out.println("-------------------"); for (Map<String, Object> map : list) { System.out.println(map.get("cj")); } } }