0% found this document useful (0 votes)
0 views

Understanding Comparable and Comparator in Java

The document explains the Comparable and Comparator interfaces in Java for sorting custom objects. Comparable is used for natural ordering within the class, while Comparator allows for custom sorting logic outside the class. Examples demonstrate sorting products by price using Comparable and by name or price using Comparator, including the use of lambda expressions for simpler code.

Uploaded by

Vpn Account
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Understanding Comparable and Comparator in Java

The document explains the Comparable and Comparator interfaces in Java for sorting custom objects. Comparable is used for natural ordering within the class, while Comparator allows for custom sorting logic outside the class. Examples demonstrate sorting products by price using Comparable and by name or price using Comparator, including the use of lambda expressions for simpler code.

Uploaded by

Vpn Account
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Understanding Comparable and Comparator in Java

In Java, sorting objects is important when working with collections like lists, sets, and maps. To sort
custom objects (like Student, Employee, Product, etc.), we use two interfaces:

1. Comparable – Used for natural ordering (default sorting).

2. Comparator – Used for custom ordering (flexible sorting).

Comparable Interface
Definition

• Comparable is an interface in java.lang package.

• It is used when an object has a single, natural way to be sorted.

• The sorting logic is inside the class itself.

• It has only one method:

int compareTo(T obj);

Comparator Interface

Definition

• Comparator is an interface in java.util package.

• It is used when an object needs multiple ways to be sorted.

• The sorting logic is outside the class in a separate class or lambda function.

• It has only one method:

int compare(T obj1, T obj2);

Use Comparable when an object has a natural sorting order that never changes.

Use Comparator when sorting logic can change or when multiple sorting options are needed.

Comparable - Sorting Products by Price

Scenario:

Imagine an e-commerce website where products are displayed in ascending order of price by
default.
package com.example.demo.compare;

import java.util.*;

class Product implements Comparable<Product> {


int id;
String name;
double price;

public Product(int id, String name, double price) {


this.id = id;
this.name = name;
this.price = price;
}

// Comparable - Sorting by Price (Default)


@Override
public int compareTo(Product other) {
return Double.compare(this.price, other.price); // Ascending order
}

@Override
public String toString() {
return id + " - " + name + " : $" + price;
}
}

public class ComparableExample {


public static void main(String[] args) {
List<Product> products = Arrays.asList(
new Product(101, "Laptop", 1200.99),
new Product(102, "Smartphone", 899.49),
new Product(103, "Headphones", 199.99)
);

// Sorting based on Comparable (Price)


Collections.sort(products);

System.out.println("Products sorted by Price (Default):");


for (Product p : products) {
System.out.println(p);
}
}
}

Key Points:

✔ Comparable is implemented in the Product class itself.


✔ Sorting is always based on price (single fixed sorting order).
✔ Uses compareTo() method inside the class.
✔ Best when there's a default sorting rule that never changes.

Comparator - Sorting Products by Name & Price

Scenario:

Now, the e-commerce website allows users to sort products by Name or Price.

package com.example.demo.compare;

import java.util.*;
//Product class (without Comparable)
class Product {
int id;
String name;
double price;

public Product(int id, String name, double price) {


this.id = id;
this.name = name;
this.price = price;
}

@Override
public String toString() {
return id + " - " + name + " : $" + price;
}
}

//Comparator to Sort by Name (Alphabetically)


class NameComparator implements Comparator<Product> {
@Override
public int compare(Product p1, Product p2) {
return p1.name.compareTo(p2.name);
}
}

//Comparator to Sort by Price (Descending)


class PriceComparatorDescending implements Comparator<Product> {
@Override
public int compare(Product p1, Product p2) {
return Double.compare(p2.price, p1.price); // Descending order
}
}

public class ComparatorExample {


public static void main(String[] args) {
List<Product> products = Arrays.asList(
new Product(101, "Laptop", 1200.99),
new Product(102, "Smartphone", 899.49),
new Product(103, "Headphones", 199.99)
);

// Sorting by Name
Collections.sort(products, new NameComparator());
System.out.println("Products sorted by Name:");
for (Product p : products) {
System.out.println(p);
}

// Sorting by Price (Descending)


Collections.sort(products, new PriceComparatorDescending());
System.out.println("\nProducts sorted by Price (Descending):");
for (Product p : products) {
System.out.println(p);
}
}
}
Using Comparator with Lambda (Shorter Code)

Java 8+ allows sorting with lambda expressions, making Comparator even simpler.
Collections.sort(products, (p1, p2) -> p1.name.compareTo(p2.name)); // Sort by
Name

Collections.sort(products, (p1, p2) -> Double.compare(p2.price, p1.price)); //


Sort by Price Descending

This eliminates the need for separate Comparator classes.

Key Points:

✔ Comparator allows multiple sorting criteria (Name, Price, etc.).


✔ Sorting logic is outside the class, making it flexible.
✔ Uses compare() method in a separate class.
✔ Best when sorting logic can change or when multiple sorting options are needed.

You might also like