87

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>();
Community
  • 1
  • 1
softwarematter
  • 28,015
  • 64
  • 169
  • 263

3 Answers3

181

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;
     }
});
Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
  • 6
    how about return(o1.degree - o2.degree);? – blitzkriegz Nov 01 '10 at 04:40
  • 24
    The proper way to do this is the way Mark coded it. Yes the simple one line of code will work 99.9 percent of the time. But you will have a problem if the result of the subtraction is a large number causing the high order bit to overflow. For example you would expect (Integer.MAX_VALUE - (-10)) to be postive, but it isn't. – camickr Nov 01 '10 at 05:54
  • @camickr What about o1.degree.compare(o2.degree)? – Ben Aaronson Jul 22 '16 at 08:49
  • @BenAaronson, should work fine if working with "Integer" objects, but it won't work if using "int" variables since the comparTo(...) method only works on objects not primitives. – camickr Jul 26 '16 at 14:29
  • @camickr Good point – Ben Aaronson Jul 26 '16 at 14:31
  • 7
    Java 8 update: Collection.sort(nodeList, Comparator.comparing(DataNode::getDegree)) or Collection.sort(nodeList, Comparator.comparingDouble(DataNode::getDegree)) if degree is an double instead of an Double – Kazaag Aug 25 '16 at 15:20
  • 4
    @Kazaag your comment should be the correct answer! :) The `Comparator.comparing...` methods can also be used with the `Stream`s API as in `nodesList.stream().sorted(Comparator.comparing(DataNode::getDegree)).collect(Collector.toList())` – yair Sep 20 '16 at 22:36
  • I'd give another upvote but 128 is a nice round number :( – agiro Dec 21 '17 at 21:15
70

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);
blitzkriegz
  • 9,258
  • 18
  • 60
  • 71
0

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

camickr
  • 321,443
  • 19
  • 166
  • 288