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
-
Possible duplicate of stackoverflow.com/questions/2784514/…Alex Jasmin– Alex Jasmin2010年11月01日 04:00:59 +00:00Commented Nov 1, 2010 at 4:00
-
2On a second tought stackoverflow.com/questions/1814095/… may be closer to thisAlex Jasmin– Alex Jasmin2010年11月01日 04:04:40 +00:00Commented Nov 1, 2010 at 4:04
-
See also stackoverflow.com/questions/2535124/…Alex Jasmin– Alex Jasmin2010年11月01日 04:08:11 +00:00Commented Nov 1, 2010 at 4:08
3 Answers 3
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
blitzkriegz
how about return(o1.degree - o2.degree);?
camickr
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.
Ben Aaronson
@camickr What about o1.degree.compare(o2.degree)?
Kazaag
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
yair
@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())
|
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
shmosel
Beware of overflow! Much safer to
return Integer.compare(this.degree, o.degree);
Christian Westbrook
For some reason I get an error if I don't input an object
ACV
this will fail because there are no checks for null. Also you don't need the brackets
Matt Westlake
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)Luke B
Your class has to implement Comparable<YourClass> and not just implement Comparable.
You can use the Bean Comparator to sort on any property in your custom class.
answered Nov 1, 2010 at 4:11
Comments
lang-java