I\'m trying to sort my custom class chromosome by the value of their score attribute which is a double. These chromosomes are stored within an ArrayList. I know I have to us
Why not use a PriorityQueue with a Comparator like this:
// your code
PriorityQueue<Chromosome> entries = new PriorityQueue<Chromosome>(1, new Comparator<Chromosome> () {
@Override
public int compare(Chromosome arg0, Chromosome arg1) {
return (Double)(arg1.getScore()).compareTo((Double)arg0.getScore());
}
});
entries.addAll(arrayListOfChromosomes);
// your code
The priority queue will then keep your data structure in sorted order.
Since java 8 you can sort list of Double elements very simple.
list.sort(Comparator.comparingDouble(Chromosome::getScore));
or
Collections.sort(list, omparator.comparingDouble(Chromosome::getScore));
If you wanna get sorted list but you don't want to change your beginning list you can do it as following:
List<Chromosome> sortedList = list.stream()
.sorted(Comparator.comparingDouble(A::getScore))
.collect(Collectors.toList());
With Java SE8 you could use lambda expression like so:
list.sort((o1, o2) -> Double.compare(o2.doubleField, o1.doubleField));
I would implement the interface Comparable:
public class Chromosome implements Comparable<Chromosome>{
private double score;
public Chromosome(double score){
this.score = score;
}
@Override
public int compareTo(Chromosome o) {
return new Double(score).compareTo( o.score);
}
@Override
public String toString() {
return String.valueOf(score);
}
}
Note that i moved score inside the Class..
Now you can use any Collection that is Sorted (like a TreeSet)
If you insist on using the Arraylist you can use:
ArrayList<Chromosome> out = new ArrayList<Chromosome>();
out.add(new Chromosome(20));
out.add(new Chromosome(15));
System.out.println(out);
Collections.sort(out);
System.out.println(out);
Result:
[0.2, 0.15]
[0.15, 0.2]
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
).