Java 根据对象字段对 ArrayList 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4066538/
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 based on an object field
提问by devnull
Possible Duplicate:
Sorting an ArrayList of Contacts
可能的重复:
对联系人的 ArrayList 进行排序
I am storing DataNode
objects in an ArrayList
. The DataNode
class has an integer field called degree
.
I want to retrieve DataNode
objects from nodeList in the increasing order of degree
. How can I do it.
我将DataNode
对象存储在ArrayList
. 该DataNode
班有一个名为整型字段degree
。我想找回DataNode
在递增的顺序从节点列表对象degree
。我该怎么做。
List<DataNode> nodeList = new ArrayList<DataNode>();
采纳答案by blitzkriegz
Modify the DataNode class so that it implements Comparable interface.
修改 DataNode 类,使其实现 Comparable 接口。
public int compareTo(DataNode o)
{
return(degree - o.degree);
}
then just use
然后只需使用
Collections.sort(nodeList);
回答by Mark Elliot
Use a custom comparator:
使用自定义比较器:
Collections.sort(nodeList, new Comparator<DataNode>(){
public int compare(DataNode o1, DataNode o2){
if(o1.degree == o2.degree)
return 0;
return o1.degree < o2.degree ? -1 : 1;
}
});
回答by camickr
You can use the Bean Comparatorto sort on any property in your custom class.
您可以使用Bean Comparator对自定义类中的任何属性进行排序。