在HashMaps的数组列表中排序

时间:2013-08-20 11:55:21

标签: java sorting collections

我有一个数据结构如下所示:

public class VResultSetBean {
   private ArrayList<RowBean> rowBeans; 
}

public class RowBean {
    private HashMap<String, Object> columns;
}

我需要根据HashMap rowBeans中某个键的值对columns进行排序。使用Java执行此操作的最有效方法是什么?

3 个答案:

答案 0 :(得分:6)

使RowBean实施Comparable并实施compareTo方法以提取该密钥的值并使用它来决定比较结果。

public class RowBean implements Comparable<RowBean> {

     private HashMap<String, Object> columns;

     @Override
     public int compareTo(RowBean other) {
          Object valOther = other.columns.get(...);
          Object valMine = columns.get(...);
          return comparison(valOther, valMine);
     }
}

RowBeanComparable后,您可以使用以下方式进行排序:

 Collections.sort(rowBeans);

答案 1 :(得分:1)

这是适合我的最终代码段。谢谢你们..

public class RowBean implements Comparable<RowBean> {
         HashMap<String, Object> columns;
        public int compareTo(RowBean other) {
             Object valOther = other.columns.get("CONVERSIONS");
             Object valMine = columns.get("CONVERSIONS");
             return comparison(valOther, valMine);
        }
        private int comparison(Object valOther, Object valMine) {
           if((Long) valMine > (Long)valOther) 
                return 1;
            else if((Long) valMine < (Long)valOther)
                return -1;
            else
                return 0;
        }
   }

答案 2 :(得分:0)

首先,没有办法比较类Object的两个对象,他们需要有一种比较的方法:这是实现接口Comparable。因此您需要将columns更改为HashMap<String, Comparable>

之后,您可以将比较方法添加到RowBean,如下所示:

class RowBean {

    private HashMap<String, Comparable> columns;

    public int compare(String column, RowBean other) {
        return columns.get(column).compareTo(other.columns.get(column));
    }

}

最后,要对列表进行排序,您可以使用匿名Comparator,这样:

List<RowBean> list = new ArrayList<>();

final String sortingColumn = "myColumn";

Collections.sort(list, new Comparator<RowBean>() {
    @Override
    public int compare(RowBean o1, RowBean o2) {
        return o1.compare(sortingColumn, o2);
    }
});