Thursday, August 4, 2016

How to sort an array using Comparable and Comparator interfaces

In order to sort an array in Java using Comparable and Comparator interfaces, first, you may create a Student class as follows :

class Student implements Comparable<Student> {
String id;
String name;
Double cgpa;

public Student(String studentId, String studentName, double studentCGPA) {
id = studentId;
name = studentName;
cgpa = studentCGPA;
}

public String toString() {
return " \n " + id + "  \t  " + name + "  \t  " + cgpa;
}

public int compareTo(Student that) {
return this.id.compareTo(that.id);
}
}

Then, you may add another class entitled ComparatorTest2 as follows :

import java.util.Arrays;
import java.util.Comparator;

class CGPAComparator implements Comparator<Student> {
    public int compare(Student s1, Student s2) {
        return (s1.cgpa.compareTo(s2.cgpa));     
    }    
}
class ComparatorTest2 {
    public static void main(String []args) {
        Student []students = {  new Student("cs011", "Lennon  ", 3.1), 
new Student("cs021", "McCartney", 3.4),  
new Student("cs012", "Harrison ", 2.7),    
new Student("cs022", "Starr ", 3.7) };

        System.out.println("Before sorting by CGPA ");
        System.out.println("Student-ID \t  Name \t  CGPA (for 4.0) ");
        System.out.println(Arrays.toString(students));
        
        Arrays.sort(students, new CGPAComparator());
        
        System.out.println("After sorting by CGPA");
        System.out.println("Student-ID \t  Name \t  CGPA (for 4.0) ");
        System.out.println(Arrays.toString(students));
    }    
}

If you run this program you would get the following output :

Before sorting by CGPA 
Student-ID  Name  CGPA (for 4.0) 
 cs011    Lennon      3.1,  
 cs021    McCartney    3.4,  
 cs012    Harrison    2.7,  
 cs022    Starr    3.7]
After sorting by CGPA
Student-ID  Name  CGPA (for 4.0) 
 cs012    Harrison    2.7,  
 cs011    Lennon      3.1,  
 cs021    McCartney    3.4,  
 cs022    Starr    3.7]

That's it, as you might have noticed, the students array was sorted according to cgpa field.

No comments:

Post a Comment