Java ArrayList Sorting - 2

If you are new to java ArrayList please check my previous post on java array list - Java Array List - 1

We are going to see how we can sort an Array List containing Student object

First create a student class :
Create a Student type Array List and add 3 student object
Run the code , the output will be [alex jones 121 3.2, james rowling 132 3.5, budapest jones 143 2.5]

Now we want to sort the array list by student cgpa lowest to maximum ( ascending)
let's see how we can achieve this :

Way 1 - using Comparable Interface

Syntax : public int compareTo(Class_name o){}

First implement Comparable :
public class Student implements Comparable<Student>

Then add this method(Ascending sort) inside Student Class : 
@Override
public int compareTo(Student student){
    if (this.cgpa > student.cgpa)
        return 1;
    else if(this.cgpa < student.cgpa)
        return -1;
    else
        return 0;
}

Then to sort the array List based on cgpa add this line inside your Main method:
Collections.sort(students);
Full code :

Main Method :
Check next tutorial on this series - Java ArrayList Sorting - 2.1

Comments

Popular Posts