Java Advanced Sorting
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java Advanced Sorting

Harine

 Java Advanced Sorting

Sorting simple data types like numbers and strings in Java is straightforward. But when working with custom objects, such as Employee, Product, or Car, you must define how those objects should be ordered.

This is where Comparator and Comparable come into play. They allow you to implement flexible, reusable, and efficient sorting logic.

Why Advanced Sorting is Needed

Consider a list of objects:

  • Sort employees by salary
  • Sort students by marks
  • Sort products by price or rating

Java cannot automatically determine the sorting logic for custom objects—you must explicitly define it.

Comparator Interface in Java

A Comparator is used to define external sorting logic. It allows you to create multiple sorting strategies without modifying the original class.

Key Features

  • Defined in java.util package
  • Contains compare(T o1, T o2) method
  • Supports multiple sorting rules
  • Ideal when you cannot modify the class

Return Values of compare()

  • Negative → First object comes before second
  • Positive → Second object comes before first
  • Zero → Both are equal

Example: Sorting Objects Using Comparator

Step 1: Create a Class

class Employee {

    String name;

    double salary;

    Employee(String name, double salary) {

       this.name = name;

       this.salary = salary;

     }

  }

Step 2: Create a Comparator

import java.util.Comparator;

class SalaryComparator implements Comparator<Employee> {

   @Override

   public int compare(Employee e1, Employee e2) {

      return Double.compare(e1.salary, e2.salary);

     }

  }

Step 3: Sort the List

import java.util.*;

public class ComparatorDemo {

   public static void main(String[] args) {

     List<Employee> employees = new ArrayList<>();

     employees.add(new Employee("Amit", 50000));

     employees.add(new Employee("Riya", 75000));

     employees.add(new Employee("Karan", 60000));

     Collections.sort(employees, new SalaryComparator());

     for (Employee e : employees) {

        System.out.println(e.name + " - " + e.salary);

       }

    }

 }

Using Lambda Expressions with Comparator

Java 8 introduced lambda expressions, making comparators more concise.

import java.util.*;

public class LambdaComparatorExample {

   public static void main(String[] args) {

      List<Employee> employees = new ArrayList<>();

      employees.add(new Employee("Anu", 45000));

      employees.add(new Employee("Raj", 65000));

      employees.add(new Employee("Meena", 55000));

      // Sort using lambda

      employees.sort((e1, e2) -> Double.compare(e1.salary, e2.salary));

      employees.forEach(e ->

         System.out.println(e.name + " - " + e.salary)

       );

     }

   }

Custom Sorting Rule Example

You can define advanced rules like prioritizing specific values.

Example: Sort Numbers (Even First, Then Odd)

import java.util.*;

public class CustomSortExample {

   public static void main(String[] args) {

     List<Integer> numbers = Arrays.asList(11, 4, 7, 20, 3, 8);

     numbers.sort((a, b) -> {

       if (a % 2 == 0 && b % 2 != 0) return -1;

       if (a % 2 != 0 && b % 2 == 0) return 1;

       return Integer.compare(a, b);

     });

     System.out.println(numbers);

    }

  }

Comparable Interface in Java

The Comparable interface defines the natural ordering of objects. It is implemented directly within the class.

Key Features

  • Located in java.lang package
  • Uses compareTo() method
  • Defines default sorting logic
  • Only one sorting rule per class

Example: Sorting Using Comparable

Step 1: Implement Comparable

class Product implements Comparable<Product> {

    String name;

    int price;

    Product(String name, int price) {

       this.name = name;

       this.price = price;

    }

     @Override

     public int compareTo(Product other) {

        return this.price - other.price;

     }

   }

Step 2: Sort the List

import java.util.*;

public class ComparableDemo {

   public static void main(String[] args) {

      List<Product> products = new ArrayList<>();

      products.add(new Product("Laptop", 80000));

      products.add(new Product("Mobile", 20000));

      products.add(new Product("Tablet", 30000));

      Collections.sort(products);

      for (Product p : products) {

          System.out.println(p.name + " - " + p.price);

         }

       }

    }

Sorting Trick for Cleaner Code

Instead of writing multiple if-else statements:

if (a > b) return 1;

if (a < b) return -1;

return 0;

You can simplify using built-in methods:

return Integer.compare(a, b);

Or for reverse order:

return Integer.compare(b, a);

When to Use What?

  • Use Comparable

→ When objects have a natural default order (e.g., sort by ID)

  • Use Comparator

→ When you need multiple sorting criteria (e.g., sort by name, salary, or age)

Our website uses cookies to enhance your experience. Learn More
Accept !