对地图列表进行排序

时间:2013-03-26 14:49:47

标签: java list sorting map

我有一张地图列表

List<Map<String, Object>> people = new ArrayList<Map<String,Object>>();

如此填充

map.put("firstName",John);
map.put("lastName",Smith);
map.put("type","1"); //type is either 1 or a 0

people.add(map);

以及填充后我要对此列表执行的操作是如此,所有人都在列表顶部键入0,所有人都在底部键入1

我知道我需要使用Comparator,但之前从未使用过,所以我不知道如何使用它或如何使用它。

有人可以帮助我吗

4 个答案:

答案 0 :(得分:4)

喜欢这个

Collections.sort( people, new Comparator<Map<String, Object>>() {
    @Override
    public int compare( Map<String, Object> o1, Map<String, Object> o2 ) {
        return (Integer.parseInt((String)o1.get( "type" ))) - 
                (Integer.parseInt((String)o2.get( "type" )));
    }
} );

然而,有很多方法可以让它变得更好。如果你不能使用Person对象来表示@Pshemo建议的地图,那么至少要为你的type属性使用合理的数据类型。最好的是枚举:

public enum PersonType {
    TYPE_1, TYPE_2
}

然后比较更清晰,更快速,更易读。

答案 1 :(得分:2)

Comparator只是一个需要实现的接口,它只包含一个需要覆盖的方法。

例如:

    List<Map<String, Object>> people = new ArrayList<Map<String,Object>>();

    Map<String, Object> map = new HashMap<String, Object>();
    map .put("firstName","John");
    map.put("lastName","Smith");
    map.put("type","1"); //type is either 1 or a 0

    people.add(map);

    Collections.sort(people, new Comparator<Map<String, Object>>() {
        @Override
        public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            // you may compare your map here
            return 0;
        }
    });

答案 2 :(得分:2)

试试这个

 Collections.sort(people, new Comparator<Map<String, String>>() {

    @Override
    public int compare(Map<String, String> m1, Map<String, String> m2) {
        return m1.get("type").compareTo(m2.get("type"));
    }
});

答案 3 :(得分:1)

您可以尝试这样:

class ListByType 
{
    private static class MyComparator implements Comparator<HashMap<String,String>>
    {
        @Override
        public int compare(HashMap mp1 , HashMap mp2)
        {
            return ((String)(mp1.get("type")).compareTo((String)mp2.get("type"));
        }
    }
    public static void main(String[] args) 
    {
        List<Map<String, String>> people = new ArrayList<Map<String,String>>();
        HashMap<String,String> map = new HashMap<String,String>();
        map.put("firstName","John");
        map.put("lastName","Smith");
        map.put("type","1"); //type is either 1 or a 0
        people.add(map);
        /*...
        ..
        ...
        Add more maps here..
        */
        //Sort the list
        Collections.sort(people,new MyComparator());
    }
}