ArrayList sort based on object field

Possible duplicate:
Sort ArrayList Address List

I am storing DataNode objects in an ArrayList . The DataNode class has an integer field called degree . I want to get DataNode objects from nodeList in ascending order degree . How can i do this.

 List<DataNode> nodeList = new ArrayList<DataNode>(); 
+51
java
Nov 01 '10 at 3:52
source share
3 answers

Modify the DataNode class so that it implements the Comparable interface.

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

then just use

 Collections.sort(nodeList); 
+48
Nov 01 '10 at 4:34
source share

Use your own 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; } }); 
+130
Nov 01 '10 at 4:08
source share

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

0
Nov 01 '10 at 4:11
source share



All Articles