1

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

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

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

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

4

3 回答 3

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);
于 2013-08-20T11:59:50.040 回答
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;
        }
   }
于 2013-08-20T13:08:36.503 回答
0

首先,没有办法比较 class 的两个对象Object,他们需要有一个比较的方法:这是实现接口Comparable。所以你需要改变columnsHashMap<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));
    }

}

最后,要对列表进行排序,您可以使用 anonym 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);
    }
});
于 2013-08-20T12:04:50.560 回答