Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Java Program to sort objects using Comparable Interface.
Consider a Student object having properties like rollno, name and marks. We will try to sort the objects based on rollno and name.
Below is the Student class definition:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
package com.sample.clearurdoubt.compare; public class Student implements Comparable<Student> { int rollno; String name; int marks; public Student(int rollno, String name, int marks) { this.rollno = rollno; this.name = name; this.marks = marks; } public int getRollno() { return rollno; } public void setRollno(int rollno) { this.rollno = rollno; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMarks() { return marks; } public void setMarks(int marks) { this.marks = marks; } @Override public int compareTo(Student student) { // sort based on rollno int i = this.getRollno() - student.getRollno(); if(i != 0) { return i; } //if the rollno are same, then sort based on name field i = this.getName().compareTo(student.getName()); return i; } } |
The Student class needs to
- implement the Comparable interface for sorting the objects.
- define the compareTo method to sort based on rollno and then on name properties.
Here is the Java program to sort the Students collection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.sample.clearurdoubt.compare; import java.util.List; import java.util.ArrayList; import java.util.Collections; public class StudentComparision { public static void main(String[] args) { //create student objects Student s1 = new Student(101, "Rahul", 560); Student s2 = new Student(102, "George", 523); Student s3 = new Student(101, "Abhay", 516); Student s4 = new Student(103, "David", 550); List<Student> students = new ArrayList<Student>(); students.add(s1); students.add(s2); students.add(s3); students.add(s4); System.out.println("=== Before Sorting ==="); for(Student s : students) { System.out.println(s.getRollno() + " :: " + s.getName() + " :: " + s.getMarks()); } System.out.println(); Collections.sort(students); // sort the collection System.out.println("=== After Sorting ==="); for(Student s : students) { System.out.println(s.getRollno() + " :: " + s.getName() + " :: " + s.getMarks()); } } } |
Output:
Happy Learning :).
Please leave a reply in case of any queries.