Sort an ArrayList based on an object field

Java

Java Problem Overview


> 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 ArrayList<DataNode>();

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsoftwarematterView Question on Stackoverflow
Solution 1 - JavaMark ElliotView Answer on Stackoverflow
Solution 2 - JavablitzkriegzView Answer on Stackoverflow
Solution 3 - JavacamickrView Answer on Stackoverflow