LinkedHashMap的订单列表

时间:2013-05-23 08:38:18

标签: java collections linkedhashmap

我有这个LinkedHashMap列表如何订购价值?

    List<LinkedHashMap<String, Object>> list = more "key:value"......

例如,在我的列表中,我有:

    [{"field1": "z", "field2":"a"},
     {"field1" : "b", "field2":"x"}]

我希望根据“field1”键的值进行排序,例如:

    [{"field1": "b", "field2":"x"},
     {"field1" : "z", "field2":"a"}]

我做了这个课:

public class OrderComparator  implements Comparator {
    String field;

    public OrderComparator (String field){
        this.field = field;
    }

    @Override
    public int compare(Object obj1, Object obj2) {
          LinkedHashMap<String, Object> a = (LinkedHashMap<String, Object>) obj1;
          LinkedHashMap<String, Object> b = (LinkedHashMap<String, Object>) obj2;

          return a.get(this.field).toString().compareTo(b.get(this.field).toString());
    }   
}

和:

Collections.sort(list, new OrderComparator(sortColumn));

是对的吗?谢谢大家!!!

2 个答案:

答案 0 :(得分:5)

答案 1 :(得分:3)

使用自定义Comparator

Collections.sort(list, new Comperator<Map<String, Object>>() {
    public int compare(Map<String, Object> a, Map<String, Object> b) {
        return a.get("field1").compareTo(b.get("field1"));
    }
});