java 基于多个属性对 ArrayList 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4310014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort an ArrayList base on multiple attributes
提问by Thang Pham
I have an ArrayList of object. The object contain attributes date
and value
. So I want to sort the objects on the date
, and for all objects in the same date I want to sort them on value
. How can I do that?
我有一个对象的 ArrayList。该对象包含属性date
和value
。所以我想date
对value
. 我怎样才能做到这一点?
回答by harto
Implement a custom Comparator
, then use Collections.sort(List, Comparator)
. It will probably look something like this:
实现自定义Comparator
,然后使用Collections.sort(List, Comparator)
. 它可能看起来像这样:
public class FooComparator implements Comparator<Foo> {
public int compare(Foo a, Foo b) {
int dateComparison = a.date.compareTo(b.date);
return dateComparison == 0 ? a.value.compareTo(b.value) : dateComparison;
}
}
Collections.sort(foos, new FooComparator());
回答by u290629
public static <T> void sort(List<T> list, final List<Comparator<T>> comparatorList) {
if (comparatorList.isEmpty()) {//Always equals, if no Comparator.
throw new IllegalArgumentException("comparatorList is empty.");
}
Comparator<T> comparator = new Comparator<T>() {
public int compare(T o1, T o2) {
for (Comparator<T> c:comparatorList) {
if (c.compare(o1, o2) > 0) {
return 1;
} else if (c.compare(o1, o2) < 0) {
return -1;
}
}
return 0;
}
};
Collections.sort(list, comparator);
}
回答by Tony
If you want sample code looks like, you can use following:
如果您希望示例代码看起来像,您可以使用以下内容:
Collections.sort(foos, new Comparator<Foo>{
public int compare(Foo a, Foo b) {
int dateComparison = a.date.compareTo(b.date);
return dateComparison == 0 ? a.value.compareTo(b.value) : dateComparison;
}
});
回答by Hovercraft Full Of Eels
If the class of the object implements Comparable, then all you need to do is properly code the compareTo method to first compare dates, and then if dates are equal, compare values, and then return the appropriate int result based on the findings.
如果对象的类实现了 Comparable,那么您需要做的就是正确编码 compareTo 方法以首先比较日期,然后如果日期相等,则比较值,然后根据结果返回适当的 int 结果。