当先锋百科网

首页 1 2 3 4 5 6 7

list map (List<Map<String,Object>>)中,根据map的某个某个key值进行排序

示例:按年龄排序,升序。代码如下:

import java.util.*;
 
public class ListMapSort {
    public static void main(String[] args) {
        List<Map<String, Object>> list = new ArrayList<>();
 
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("name","laowang");
        map1.put("age",25);
 
        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("name","wangliu");
        map2.put("age",23);
 
        HashMap<String, Object> map3 = new HashMap<>();
        map3.put("name","laoliu");
        map3.put("age",24);
 
        list.add(map1);
        list.add(map2);
        list.add(map3);
        //排序前
        System.out.println("排序前:");
        for (Map<String, Object> map : list) {
            System.out.println(map.get("age"));
        }
 
        Collections.sort(list, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Integer age1 = (Integer) o1.get("age");
                Integer age2 = (Integer) o2.get("age");
                return age1.compareTo(age2);//升序
            }
        });
 
        //排序后
        System.out.println("排序后:");
        for (Map<String, Object> map : list) {
            System.out.println(map.get("age"));
        }
    }
}

运行结果:
在这里插入图片描述