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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:11:26  来源:igfitidea点击:

Sort an ArrayList based on an object field

java

提问by devnull

Possible Duplicate:
Sorting an ArrayList of Contacts

可能的重复:
对联系人的 ArrayList 进行排序

I am storing DataNodeobjects in an ArrayList. The DataNodeclass has an integer field called degree. I want to retrieve DataNodeobjects 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对自定义类中的任何属性进行排序。