Comparable and Comparator Interface in Java

Published on August 6, 2024

import java.util.*;
import java.util.stream.Collectors;
 
class Product implements Comparable<Product> {
    private String name;
    private double price;
 
    public Product() {}
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public double getPrice() {
        return price;
    }
 
    public void setPrice(double price) {
        this.price = price;
    }
 
    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
 
    @Override
    public String toString() {
        return "(" + name + ", " + price + ")";
    }
 
    @Override
    public int compareTo(Product prod) {
        return this.getName().compareTo(prod.getName());
    }
 
    class PriceComparator implements Comparator<Product> {
        @Override
        public int compare(Product prod1, Product prod2) {
            if (prod1.getPrice() > prod2.getPrice()) {
                return -1;
            } else if (prod1.getPrice() < prod2.getPrice()) {
                return 1;
            } else {
                return 0;
            }
            // return prod1.getPrice().compareTo(prod2.compare());
        }
    }
}
 
public class Main {
    public static void main(String[] args) {
        List<Product> products = Arrays.asList(
            new Product("apple", 21.22),
            new Product("zerox", 33.2),
            new Product("hp", 40),
            new Product("adobe", 3),
            new Product("book", 44),
            new Product("iphone", 23)
        );
 
        System.out.println("products: " + products);
        Collections.sort(products);
        System.out.println("products sorted by name: " + products);
 
        Collections.sort(products, new Product().new PriceComparator());
        System.out.println("products sorted by price: " + products);
    }
}

Output:

products[(apple,21.22), (zerox,33.2), (hp,40.0), (adobe,3.0), (book,44.0), (iphone,23.0)]
products sort by name[(adobe,3.0), (apple,21.22), (book,44.0), (hp,40.0), (iphone,23.0), (zerox,33.2)]
products sort by price[(book,44.0), (hp,40.0), (zerox,33.2), (iphone,23.0), (apple,21.22), (adobe,3.0)]