Sorting a double value of an object within an arrayList
To use a Comparator
:
Collections.sort(myList, new Comparator<Chromosome>() {
@Override
public int compare(Chromosome c1, Chromosome c2) {
return Double.compare(c1.getScore(), c2.getScore());
}
});
If you plan on sorting numerous List
s in this way I would suggest having Chromosome
implement the Comparable
interface (in which case you could simply call Collections.sort(myList)
, without the need of specifying an explicit Comparator
).
With Java SE8 you could use lambda expression like so:
list.sort((o1, o2) -> Double.compare(o2.doubleField, o1.doubleField));