package test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; public class java_ListMapSort { public static void main(String[] args) { // TODO Auto-generated method stub List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("name", "p"); map1.put("age", "5"); Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("name", "h"); map2.put("age", "12"); Map<String, Object> map3 = new HashMap<String, Object>(); map3.put("name", "f"); map3.put("age", "31"); list.add(map1); list.add(map3); list.add(map2); //排序前 for (Map<String, Object> map : list) { System.out.println(map.get("age")); } Collections.sort(list, new Comparator<Map<String, Object>>() { public int compare(Map<String, Object> o1, Map<String, Object> o2) { Integer age1= Integer.valueOf(o1.get("age").toString()) ;//age1是从你list里面拿出来的第一个 age Integer age2= Integer.valueOf(o2.get("age").toString()) ; //age1是从你list里面拿出来的第二个age return age1.compareTo(age2); //return age2.compareTo(age1);为降序 } }); //排序后 System.out.println("-------------------"); for (Map<String, Object> map : list) { System.out.println(map.get("age")); } } }
时间: 2024-10-08 09:16:38