[英]Sorting in a Array List of HashMaps
I have a data Structure as shown below: 我有一个数据结构,如下所示:
public class VResultSetBean {
private ArrayList<RowBean> rowBeans;
}
public class RowBean {
private HashMap<String, Object> columns;
}
I need to sort rowBeans
based on value of one of the keys in HashMap columns
. 我需要根据HashMap
columns
键之一的值对rowBeans
进行排序。 What is the most efficient way to do this with Java? 用Java做到这一点的最有效方法是什么?
Make RowBean
implement Comparable
and implement the compareTo
method to pull out the value of that key and use it to decide the result of the comparison. 使
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);
}
}
Once RowBean
is a Comparable
you can sort using: 一旦
RowBean
是可Comparable
您可以使用以下方法进行排序:
Collections.sort(rowBeans);
This is the final code snippet that worked for me. 这是对我有用的最终代码段。 Thanks guys..
多谢你们..
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;
}
}
First, there is no way to compare two objects of class Object
, they need to have a way to get compared: this is implementing the interface Comparable
. 首先,无法比较
Object
类的两个对象,它们需要有一种比较的方法:这是实现Comparable
接口。 so you would need to change columns
to be HashMap<String, Comparable>
. 因此您需要将
columns
更改为HashMap<String, Comparable>
。
After that, you could add a comparing method to RowBean
like this: 之后,您可以向
RowBean
添加一个比较方法,如下所示:
class RowBean {
private HashMap<String, Comparable> columns;
public int compare(String column, RowBean other) {
return columns.get(column).compareTo(other.columns.get(column));
}
}
And finally, to sort your list you could use an anonym Comparator
, this way: 最后,要对列表进行排序,您可以使用匿名
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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.