MainMenu

Home Java Overview Maven Tutorials

Friday 11 October 2024

Comparable and Comparator Interface in Java




Hello Friends,

In java, when we want to sort a collection, we use Class “Collections” and static method “sort()”
For example : List list = new ArraysList();
Collections.sort(list);
Now all the elements of the list will be sorted as per alphabetic order or numeric order.
But what if a list has objects then list items will be compared and which one will go first in list??
So , to sort the objects, we need to specify a rule based on that object should be sorted.
The “Comparator” and “Comparable” interface allow us to specify what rule is used to sort the objects.

FeatureComparableComparator
Interfacejava.lang.Comparablejava.util.Comparator
MethodcompareTo(T o)compare(T o1, T o2)
Natural OrderDefines natural ordering within the classDefines custom ordering outside the class
Single/MultipleCan only have one natural orderCan define multiple comparison methods
UsageUsed when you have one "natural" way to compareUsed for custom sorting logic or multiple comparisons


1. Comparable Interface

Purpose: Used to define a natural ordering of objects.
Method: Requires implementation of the method compareTo(Object o).
Usage: A class implements Comparable when its objects are supposed to be ordered in a natural way (e.g., alphabetical for strings, numerical for numbers).
Modification: This affects the class itself, meaning the comparison logic is part of the class definition.



2. Comparator Interface

Purpose: Used to define a custom or multiple orderings for objects.
Method: Requires implementation of the method compare(Object o1, Object o2).
Usage: Comparator is typically used when you want to define multiple ways of comparing objects or when you want to compare objects of a class that you do not control (e.g., a library class).
Modification: The comparison logic is external to the class being compared.

Comparable with example :




public class Vehicle implements Comparable<Vehicle>{
private int vehiclenumber;
private String vehiclename;
private int vehicleyear;
public Vehicle(int vehiclenumber, String vehiclename, int vehicleyear){
this.vehiclenumber = vehiclenumber;
this.vehiclename = vehiclename;
this.vehicleyear = vehicleyear;
}
public String toString(){
return "vehicle{"+
"vehiclenumber='" + vehiclenumber+ '\''+
", vehiclename='" + vehiclename+ '\''+
", vehicleyear=" + vehicleyear+
'}';
}

@Override
public int compareTo(@NotNull Vehicle o) {
return this.vehiclenumber - o.vehiclenumber;
}
}

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

public class comparatordemoa {
public static void main(String[] args){
List list = new ArrayList();
list.add(10);
list.add(20);
list.add(9);
list.add(15);
System.out.println(list);
Collections.sort(list);
System.out.println(list);
List list2 = new ArrayList();
list2.add(new vehical(2345, "ford", 2024));
list2.add(new vehical(3456, "kia", 2023));
list2.add(new vehical(5678, "suzuki", 2025));
System.out.println(list2);
Collections.sort(list2);
System.out.println(list2);
}
}

Comparator with example :

public class Vehicle2 {
public int getVehiclenumber() {
return vehiclenumber;
}
public void setVehiclenumber(int vehiclenumber) {
this.vehiclenumber = vehiclenumber;
}
public String getVehiclename() {
return vehiclename;
}
public void setVehiclename(String vehiclename) {
this.vehiclename = vehiclename;
}
public int getVehicleyear() {
return vehicleyear;
}

public void setVehicleyear(int vehicleyear) {
this.vehicleyear = vehicleyear;
}

private int vehiclenumber;
private String vehiclename;
private int vehicleyear;

public Vehicle2(int vehiclenumber, String vehiclename, int vehicleyear){
this.vehiclenumber = vehiclenumber;
this.vehiclename = vehiclename;
this.vehicleyear = vehicleyear;
}

public String toString(){
return "vehicle{"+
"vehiclenumber='" + vehiclenumber+ '\''+
", vehiclename='" + vehiclename+ '\''+
", vehicleyear=" + vehicleyear+
'}';
}
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ComparableDemo {
public static void main(String[] args){
List list = new ArrayList();
list.add("Amit");
list.add("Baji");
list.add("Nishant");
list.add("Diraaj");
list.add("Chandan");
System.out.println(list);
Collections.sort(list);
System.out.println(list);
List list1 = new ArrayList();
list1.add(new Vehicle(10,"ford", 2022));
list1.add(new Vehicle(15,"Hundai", 2023));
list1.add(new Vehicle(5,"Honda", 2026));
System.out.println(list1);
Collections.sort(list1);
System.out.println(list1);
List list2 = new ArrayList();
list2.add(new Vehicle2(10,"City", 2022));
list2.add(new Vehicle2(15,"Baleno", 2023));
list2.add(new Vehicle2(5,"Accent", 2026));
System.out.println(list2);
Collections.sort(list2, new CompratorDemo());
System.out.println(list2);
}
}

public class CompratorDemo implements Comparator<Vehicle2> {

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

Example :


Tags:

Example of Comparable interface in java

Example of Comparator interface in java

Comparable vs comparator in java

Adavntage of Comparator over Comparable interface in java

No comments:

Post a Comment