stevenclitler stevenclitler - 11 months ago 47
Java Question

Compare and order objects in an arraylist, java

I have an

composed of
objects. These objects contain first name, last name, lab grade, project grade, exam grade, and total grade. I am trying to write a function that sorts the
objects in the
based on their total grade.

Here's my Student class:

public class Student {

// fields
private String firstname;
private String lastname;
private int labgrade;
private int projectgrade;
private int examgrade;
private int totalgrade;

// constructor
public Student(String firstname, String lastname, int labgrade,
int projectgrade, int examgrade) {
this.firstname = firstname;
this.lastname = lastname;
this.labgrade = labgrade;
this.examgrade = examgrade;
this.totalgrade = labgrade + projectgrade + examgrade;

// method
public String toString() {
String s = firstname + " " + lastname + " has a total grade of "
+ totalgrade;
return s;
public int compareTo(Student s) {
return (totalgrade = s.totalgrade);

And here's what I tried to do to sort:

private ArrayList<Student> arraylist = new ArrayList<Student>();
public void SortStudent() {

But that doesn't work because it says it can only work on Lists not ArrayLists. Any help to fix my


ArrayList is a List, the problem is that Student does not implement Comparable, and you didn't define the compareTo method, which you need to do to use the sort method from Collections.
You could do something similar to this:

public class Student implements Comparable<Student> {
    //... the rest of the class
    public int compareTo(Student s) {
        return, s.grade);

Another option would be to use lambda expressions with the method Collections.sort(List<T>, Comparator<? super T> c), where you don't need to implement Comparable:

public void sortStudent() {
    Collections.sort(arraylist, (s1, s2) ->, s2.grade));