导航

List<Map> 排序

Posted on 2017-03-09 14:17  _eve  阅读(2956)  评论(0编辑  收藏  举报
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 Test2 {
 
    public static void main(String[] args) {
 
        List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();
 
        Map<Object, Object> map = new HashMap<Object, Object>();
 
        Map<Object, Object> map1 = new HashMap<Object, Object>();
        Map<Object, Object> map2 = new HashMap<Object, Object>();
        Map<Object, Object> map3 = new HashMap<Object, Object>();
 
        map.put("number", 11);
        map1.put("number", 2);
        map2.put("number", 44);
        map3.put("number", 3);
        list.add(map);
        list.add(map1);
        list.add(map2);
        list.add(map3);
 
        Collections.sort(list, new Comparator<Map<Object, Object>>() {
 
            public int compare(Map<Object, Object> o1, Map<Object, Object> o2) {
 
                int map1value = (Integer) o1.get("number");
                int map2value = (Integer) o2.get("number");
 
                return map1value - map2value;
            }
        });
        System.out.println(list);
    }
}

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 Test3 {
    public static void main(String[] args) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
 
        list.add(getData(0));
        list.add(getData(3));
        list.add(getData(05));
        list.add(getData(6));
        list.add(getData(2));
 
        System.out.println("排序前" + list);
 
        Collections.sort(list, new Comparator<Map<String, String>>() {
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                return o1.get("countScore").compareTo(o2.get("countScore"));
            }
        });
 
        System.out.println("排序后" + list);
    }
 
    private static Map<String, String> getData(int num) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("countScore", String.valueOf(num));
        return map;
    }
}