我有一个数据结构如下所示:
public class VResultSetBean {
private ArrayList<RowBean> rowBeans;
}
public class RowBean {
private HashMap<String, Object> columns;
}
我需要根据HashMap rowBeans
中某个键的值对columns
进行排序。使用Java执行此操作的最有效方法是什么?
答案 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);
}
}
RowBean
为Comparable
后,您可以使用以下方式进行排序:
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);
}
});