I'm trying to sort by last name in descending order, then grade, and have been following this example.
I am only getting through the last name sort however and not the grade sort. What am I not getting?
@Override
public int compare(Student o1, Student o2) {
int c;
c = o1.getLastName().compareToIgnoreCase(o2.getLastName());
if (c == 0) {
c = Double.compare(o1.getGrade(), o2.getGrade());
}
return c;
}
I'm not totally getting how the mentioned example works in terms of c == 0, as c never equals zero while it's sorting. This makes me understand why the grades aren't sorting, but this doesn't get me where I need.
The sort is executed here :
@Override
public void execute(List<Student> list) {
LastNameComparator cmp = new LastNameComparator(studentList);
Collections.sort(studentList, cmp);
}
And the testing class is like this:
public static void main(String[] args) {
// TODO code application logic here
for (int i = 0; i < 20; i++) {
Student student = new Student(randomInteger(1,50), NameGenerator.generateName(), NameGenerator.generateName(), Math.round(Math.random()*10.0)/10.0);
studentList.add(student);
}
System.out.println("--Unsorted--");
for (Student student : studentList) {
System.out.println(student.getStudentID());
System.out.println(student.getFirstName());
System.out.println(student.getLastName());
System.out.println(student.getGrade());
}
Command sortLastName = new LastNameComparator(studentList);
sortLastName.execute(studentList);
System.out.println("--Sorted--");
for (Student student : studentList) {
System.out.println(student.getStudentID());
System.out.println(student.getFirstName());
System.out.println(student.getLastName());
System.out.println(student.getGrade());
}
}
The names are generated like this. I got it from here:
public class NameGenerator {
private static String[] Beginning = { "Kr", "Ca", "Ra", "Mrok", "Cru",
"Ray", "Bre", "Zed", "Drak", "Mor", "Jag", "Mer", "Jar", "Mjol",
"Zork", "Mad", "Cry", "Zur", "Creo", "Azak", "Azur", "Rei", "Cro",
"Mar", "Luk" };
private static String[] Middle = { "air", "ir", "mi", "sor", "mee", "clo",
"red", "cra", "ark", "arc", "miri", "lori", "cres", "mur", "zer",
"marac", "zoir", "slamar", "salmar", "urak" };
private static String[] End = { "d", "ed", "ark", "arc", "es", "er", "der",
"tron", "med", "ure", "zur", "cred", "mur" };
private static Random rand = new Random();
public static String generateName() {
return Beginning[rand.nextInt(Beginning.length)] +
Middle[rand.nextInt(Middle.length)]+
End[rand.nextInt(End.length)];
}
}
UPDATE I'm understanding that this will only work if the names are the same. This is where this isn't working for me, as the random name generator has a slim chance of generating the same name twice. I am looking into how I can get the list sorted by last name in descending order, then by grade, whether or not the names are the same. If the names are the same, higher grade comes first.