I want to write a program such that:
1) A class Student (with name, id, batch)
2) In that class, write a int compareByBatch(Student s1, Student s2) method
3) Use collections.sort() to compare objects
4) Use the compareByBatch method as the second argument to the sort method.
I am able to write the program as follows:
Student.java class file:
public class Student {
private String id;
private String name;
private int Batch;
//Added a class constructor getters and setters
public static Comparator<Student> studBatch = new Comparator<Student>() {
public int compare(Student s1, Employee s2) {
int batch1 = s1.getBatch();
int batch2 = s2.getBatch();
//For ascending order
return batch1-batch2;
}};
}
Then, in the Main file added the following:
Created an ArrayList and added records in it:
ArrayList<Student> stud = new ArrayList<>();
stud.add(new Student("A01", "John Doe", 101));
stud.add(new Student("A02", "Mike Gaman", 102));
Collections.sort(stud, stud.studBatch);
The above code works fine and I get the sorted records by Batch.
But, my question is, how to write a code as per my coding requirements which I have mentioned in the beginning i.e. using compareByBatch() method inside Student class and using in with Collections.sort()? I need to pass a method reference from object class as the second argument for the Collections.sort().