91

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>();
asked Nov 1, 2010 at 3:52
3

3 Answers 3

185

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;
 }
});
answered Nov 1, 2010 at 4:08

8 Comments

how about return(o1.degree - o2.degree);?
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 What about o1.degree.compare(o2.degree)?
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 your comment should be the correct answer! :) The Comparator.comparing... methods can also be used with the Streams API as in nodesList.stream().sorted(Comparator.comparing(DataNode::getDegree)).collect(Collector.toList())
|
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);
answered Nov 1, 2010 at 4:34

5 Comments

Beware of overflow! Much safer to return Integer.compare(this.degree, o.degree);
For some reason I get an error if I don't input an object
this will fail because there are no checks for null. Also you don't need the brackets
I'm getting an issue where I have to use Object as the type in the method call, and I can't cast that to my object type (DataNode in this example)
Your class has to implement Comparable<YourClass> and not just implement Comparable.
0

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

answered Nov 1, 2010 at 4:11

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.