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 use a comparator but I've read so many differing opinions online in the last hour that I'm utterly confused.
Attached is my code, if someone could point me in the right direction I would be much appreciated.
public class Chromosome
{
public Gene[] genes;
public double score;
public Chromosome(int l)
{
genes = new Gene[l];
}
public int getLength()
{
return genes.length;
}
public void printChromo()
{
for(int i=0;i<this.genes.length;i++)
{
System.out.println(""+this.genes[i].teacher+","+
this.genes[i].lecture+","+
this.genes[i].room+","+
this.genes[i].time+"");
}
}
public void setScore(double score)
{
this.score=score;
}
public double getScore()
{
return this.score;
}
}
Don't know this make a difference but the score can only be a double between and including 0.0 to 1.0
With Java SE8 you could use lambda expression like so:
Since java 8 you can sort list of Double elements very simple.
or
If you wanna get sorted list but you don't want to change your beginning list you can do it as following:
I would implement the interface Comparable:
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:
Result:
To use a
Comparator
:If you plan on sorting numerous
List
s in this way I would suggest havingChromosome
implement theComparable
interface (in which case you could simply callCollections.sort(myList)
, without the need of specifying an explicitComparator
).Why not use a PriorityQueue with a Comparator like this:
The priority queue will then keep your data structure in sorted order.