开发者

Sort an ArrayList based on an object field [duplicate]

开发者 https://www.devze.com 2023-01-22 15:46 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Sorting an ArrayList of Contacts
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Sorting an ArrayList of Contacts

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.

List<DataNode> nodeList = new Ar开发者_C百科rayList<DataNode>();


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;
     }
});


Modify the DataNode class so that it implements Comparable interface.

public int compareTo(DataNode o)
{
     return(degree - o.degree);
}

then just use

Collections.sort(nodeList);


You can use the Bean Comparator to sort on any property in your custom class.

0

精彩评论

暂无评论...
验证码 换一张
取 消