Sort List of Collections in Java using Comparable interface

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface to compare its instances.

Example

package collections;

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

class Student implements Comparable<Student> {
	int ID;
	String name;
	char grade;

	public Student(int iD, String name, char grade) {
		super();
		ID = iD;
		this.name = name;
		this.grade = grade;
	}

	@Override
	public String toString() {
		return "Student [ID=" + ID + ", name=" + name + ", grade=" + grade + "]";
	}

	@Override
	public int compareTo(Student o) {
		int result = this.ID - o.ID; // Sorting by ID
		return result;
	}
}

public class StudentSort {

	public static void main(String[] args) {

		List<Student> stu = new ArrayList<>();
		stu.add(new Student(10, "General Motors", 'A'));
		stu.add(new Student(100, "Ferrari", 'B'));
		stu.add(new Student(5, "Mustang", 'C'));
		stu.add(new Student(5, "Ford", 'F'));

		System.out.println("Before");
		printCollections(stu);
		Collections.sort(stu);
		System.out.println("After");
		printCollections(stu);
	}

	private static void printCollections(List<Student> stu) {
		for (Student s : stu)
			System.out.println(s);
	}
}

Output

Before
Student [ID=10, name=General Motors, grade=A]
Student [ID=100, name=Ferrari, grade=B]
Student [ID=5, name=Mustang, grade=C]
Student [ID=5, name=Ford, grade=F]
After
Student [ID=5, name=Mustang, grade=C]
Student [ID=5, name=Ford, grade=F]
Student [ID=10, name=General Motors, grade=A]
Student [ID=100, name=Ferrari, grade=B]

In the above example, ID 5 is same for Mustang and Ford, if we want to sort first by ID and if the ID’s are same same then sort by name. Then we have to modify our compareTo method. Code is explained in next article Sort by first and then by second

Leave a Reply

Your email address will not be published. Required fields are marked *