Use comparable to sort first by 1st field and then second field in Java

In order to sort first by ID and if the Id’s are same then sort by name. Please follow the code

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

		if (result == 0) { // if both the integer values are same, then sort by name
			result = this.name.compareTo(o.name); // comparing strings
		}

		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=Ford, grade=F]
Student [ID=5, name=Mustang, grade=C]
Student [ID=10, name=General Motors, grade=A]
Student [ID=100, name=Ferrari, grade=B]

Leave a Reply

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