Java-Comparable and Comparator with example

Comparable Interface and Comparator Interface in java are very useful for sorting the collection of objects

The Comparable Interface in Java with Example
The Comparable interface has the compareTo(T obj) method which is used by sorting methods, you can check any Wrapper, String, or Date class to confirm this. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as an argument. Comparable is present in java.lang package. We can sort the list elements of Comparable type by Collections.sort(List) method.

Example:
Consider an Employee class that has members like, username,userid,   year of joining. Suppose we wish to sort a list of Employees based on the year of joining. We can implement the Comparable interface with the Employee class, and we override the method compareTo() of Comparable interface. 
Employee.java

//A Java program to demonstrate the use of Comparable
//A class 'Employee' that implements Comparable
class Employee implements Comparable<Employee> {

private String username;
private String userid;
private int yearofjoin;

/* Used to sort employees by year of join */
public int compareTo(Employee m) {
return this.yearofjoin - m.yearofjoin;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getUserid() {
return userid;
}

public void setUserid(String userid) {
this.userid = userid;
}

public int getYearofjoin() {
return yearofjoin;
}

public void setYearofjoin(int yearofjoin) {
this.yearofjoin = yearofjoin;
}

public Employee(String username, String userid, int yearofjoin) {
super();
this.username = username;
this.userid = userid;
this.yearofjoin = yearofjoin;
}
}

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

//Test Class
public class TestClass {
public static void main(String[] args) {
List<Employee> list = new ArrayList<Employee>();
list.add(new Employee("sibin", "sibin@gmail.com", 2015));
list.add(new Employee("Rahul", "rahul@gmail.com", 1977));
list.add(new Employee("John", "John@gmail.com", 1980));
list.add(new Employee("Jannet", "Jannet@gmail.com", 1983));
Collections.sort(list);
System.out.println("Employees after sorting : ");
for (Employee employee : list) {
System.out.println(employee.getUserid() + " " + employee.getUsername() + " " + employee.getYearofjoin());
}
}
}

Output:

Employees after sorting : 
rahul@gmail.com Rahul 1977
John@gmail.com John 1980
Jannet@gmail.com Jannet 1983
sibin@gmail.com sibin 2015

The comparator in Java with example
In Comparator, we can sort the collection on the basis of multiple elements such as id, name, and age, etc.. It’s a separate class. We create multiple separate classes (that implement Comparator) to compare by different members.
Comparator provides compare() method to sort elements.A Comparator is present in the java. util package. We can sort the list elements of Comparator type by Collections.sort(List, Comparator) method.
Example:
Employee.java
// A class 'Employee' that implements Comparable
class Employee implements Comparable<Employee> {
private int age;
private String name;
private int yearofjoin;

// Used to sort employees by year of join
public int compareTo(Employee m) {
return this.yearofjoin - m.yearofjoin;
}

// Constructor
public Employee(int age, String name, int yearofjoin) {
super();
this.age = age;
this.name = name;
this.yearofjoin = yearofjoin;
}

// Getter methods for accessing private data
public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getYearofjoin() {
return yearofjoin;
}

public void setYearofjoin(int yearofjoin) {
this.yearofjoin = yearofjoin;
}
}

import java.util.Comparator;

//Class to compare Employees by age
class AgeCompare implements Comparator<Employee> {

@Override
public int compare(Employee o1, Employee o2) {
if (o1.getAge() < o2.getAge())
return -1;
if (o1.getAge() > o2.getAge())
return 1;
else
return 0;
}
}

NameCompare.java
import java.util.Comparator;

//Class to compare Employees by name
class NameCompare implements Comparator<Employee> {

@Override
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}

Main class

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

// Driver class
class Main {
public static void main(String[] args) {
ArrayList<Employee> list = new ArrayList<Employee>();
list.add(new Employee(17, "sibin", 1927));
list.add(new Employee(19, "Rahul", 1977));
list.add(new Employee(10, "Joy", 1980));
list.add(new Employee(9, "Scott", 1983));

// Sort by age : (1) Create an object of ageCompare
// (2) Call Collections.sort
// (3) Print Sorted list
System.out.println("Sorted by age");
AgeCompare ageCompare = new AgeCompare();
Collections.sort(list, ageCompare);
for (Employee employee : list)
System.out.println(employee.getAge() + " " + employee.getName() + " " + employee.getYearofjoin());

System.out.println("\nSorted by name");
NameCompare nameCompare = new NameCompare();
Collections.sort(list, nameCompare);
for (Employee employee : list)
System.out.println(employee.getName() + " " + employee.getAge() + " " + employee.getYearofjoin());

// Uses Comparable to sort by year of join
System.out.println("\nSorted by year");
Collections.sort(list);
for (Employee employee : list)
System.out.println(employee.getYearofjoin() + " " + employee.getAge() + " " + employee.getName() + " ");
}
}

Output:

Sorted by age
9 Scott 1983
10 Joy 1980
17 sibin 1927
19 Rahul 1977

Sorted by name
Joy 10 1980
Rahul 19 1977
Scott 9 1983
sibin 17 1927

Sorted by year
1927 17 sibin 
1977 19 Rahul 
1980 10 Joy 
1983 9 Scott 

by sibin

Comments

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

ReactJS - Bootstrap - Buttons

Java - How to Count the Number of Occurrences of Substring in a String

Spring Core | BeanFactoryPostProcessor | Example

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

Custom Exception Handling in Quarkus REST API

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024