Java Advanced Sorting


Sorting is one of the most common tasks in programming. In Java, we often need to arrange data in a particular order — either ascending or descending. The basic sorting methods, like Collections.sort() or Arrays.sort(), are good for simple lists. However, when you start working with complex objects or need more control over sorting logic, Java offers advanced sorting techniques using comparators, lambdas, and streams.

This tutorial explains how to perform advanced sorting in Java using custom comparators, lambda expressions, and the Stream API.

What Is Sorting in Java?

Sorting means arranging data in a specific order. You can sort:

  • Numbers (e.g., ascending or descending)

  • Strings (alphabetical order)

  • Objects (based on one or more fields like name, age, or salary)

In Java, sorting is mainly handled through:

  1. Comparable interface

  2. Comparator interface

  3. Lambda expressions and Stream API

Using Comparable Interface

The Comparable interface is used when you want to define the natural order for a class. It contains one method:

public int compareTo(T obj);

If you implement this interface in a class, objects of that class can be sorted automatically.

Example 1: Sorting Using Comparable

import java.util.*;

class Student implements Comparable<Student> {
    String name;
    int marks;

    Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }

    public int compareTo(Student s) {
        return this.marks - s.marks; // ascending order
    }
}

public class ComparableExample {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student("Riya", 85));
        list.add(new Student("Meera", 90));
        list.add(new Student("Anjali", 75));

        Collections.sort(list);

        for (Student s : list) {
            System.out.println(s.name + " - " + s.marks);
        }
    }
}

Output:

Anjali - 75
Riya - 85
Meera - 90

This method works well when you have a single natural sorting order. But what if you want to sort by name or descending marks? That’s where Comparator comes in.

Using Comparator Interface

The Comparator interface allows you to define multiple sorting strategies. It has two main methods:

int compare(T obj1, T obj2);
boolean equals(Object obj);

You can use it to sort objects without modifying their original class.

Example 2: Sorting Using Comparator

import java.util.*;

class Student {
    String name;
    int marks;

    Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }
}

public class ComparatorExample {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student("Riya", 85),
            new Student("Meera", 90),
            new Student("Anjali", 75)
        );

        Comparator<Student> sortByMarksDesc = (s1, s2) -> s2.marks - s1.marks;

        Collections.sort(students, sortByMarksDesc);

        for (Student s : students) {
            System.out.println(s.name + " - " + s.marks);
        }
    }
}

Output:

Meera - 90
Riya - 85
Anjali - 75

This is more flexible than Comparable, as you can create different comparators for different needs.

Sorting Using Lambda Expressions

Before Java 8, you had to use anonymous classes for custom sorting. With lambdas, sorting becomes simpler and cleaner.

Example 3: Lambda Simplified Sorting

import java.util.*;

public class LambdaSort {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Riya", "Meera", "Anjali", "Aarti");

        names.sort((a, b) -> a.compareToIgnoreCase(b));

        System.out.println("Sorted List: " + names);
    }
}

Output:

Sorted List: [Aarti, Anjali, Meera, Riya]

This approach removes unnecessary boilerplate code and makes sorting more readable.

Sorting Objects Using Multiple Fields

Sometimes you need to sort data by more than one field, like sorting employees first by department, then by salary.

Example 4: Sort by Multiple Criteria

import java.util.*;

class Employee {
    String name;
    String department;
    int salary;

    Employee(String name, String department, int salary) {
        this.name = name;
        this.department = department;
        this.salary = salary;
    }
}

public class MultiSortExample {
    public static void main(String[] args) {
        List<Employee> list = Arrays.asList(
            new Employee("Riya", "IT", 40000),
            new Employee("Meera", "HR", 45000),
            new Employee("Anjali", "IT", 50000),
            new Employee("Aarti", "HR", 40000)
        );

        list.sort(Comparator.comparing(Employee::getDepartment)
                            .thenComparing(Employee::getSalary));

        for (Employee e : list) {
            System.out.println(e.department + " - " + e.name + " - " + e.salary);
        }
    }
}

(If your class doesn’t have getters, you can replace Employee::getDepartment with a lambda like (e1, e2) -> e1.department.compareTo(e2.department).)

Sorting Using Stream API

Java’s Stream API provides an even more modern way to sort data. You can use it to sort and collect results without modifying the original list.

Example 5: Stream Sorting Example

import java.util.*;
import java.util.stream.*;

public class StreamSortExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(9, 3, 5, 1, 8, 6);

        List<Integer> sorted = numbers.stream()
                                      .sorted()
                                      .collect(Collectors.toList());

        System.out.println("Ascending: " + sorted);

        List<Integer> desc = numbers.stream()
                                    .sorted((a, b) -> b - a)
                                    .collect(Collectors.toList());

        System.out.println("Descending: " + desc);
    }
}

Output:

Ascending: [1, 3, 5, 6, 8, 9]
Descending: [9, 8, 6, 5, 3, 1]

Sorting Maps by Key or Value

Maps in Java don’t store elements in order. But you can sort them by key or value using streams.

Example 6: Sort Map by Value

import java.util.*;
import java.util.stream.*;

public class MapSortExample {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Riya", 85);
        scores.put("Meera", 90);
        scores.put("Anjali", 75);

        scores.entrySet().stream()
              .sorted(Map.Entry.comparingByValue())
              .forEach(entry -> System.out.println(entry.getKey() + " = " + entry.getValue()));
    }
}

Output:

Anjali = 75
Riya = 85
Meera = 90

Sorting Arrays with Custom Logic

You can also sort arrays using Arrays.sort() with a custom comparator.

Example 7: Sorting Array with Comparator

import java.util.*;

public class ArraySortExample {
    public static void main(String[] args) {
        String[] cities = {"Delhi", "Pune", "Mumbai", "Agra"};

        Arrays.sort(cities, (a, b) -> b.compareTo(a));

        System.out.println("Sorted Cities (Descending): " + Arrays.toString(cities));
    }
}

Output:

Sorted Cities (Descending): [Pune, Mumbai, Delhi, Agra]

Summary of the Tutorial

Advanced sorting in Java gives you flexibility and control.
You can:

  • Use Comparable for natural order.

  • Use Comparator for custom logic.

  • Use Lambda and Stream API for modern, concise syntax.

  • Sort arrays, lists, and maps easily.

Sorting is one of the most essential skills in Java — especially when working with collections and databases.


Practice Questions

  1. Write a Java program to sort an array of integers in both ascending and descending order using a custom comparator.

  2. Create a Student class with name and marks. Sort the list of students by marks in descending order using a lambda expression.

  3. Write a program to sort a list of strings by their length using the Comparator interface.

  4. Create a list of employees with fields name, department, and salary. Sort them first by department name, then by salary using Comparator.comparing() and thenComparing().

  5. Write a program to sort a Map<String, Integer> by its keys alphabetically.

  6. Write a program to sort a Map<String, Integer> by its values using the Java Stream API.

  7. Use Arrays.sort() with a custom comparator to sort an array of city names in reverse alphabetical order.

  8. Write a program using the Stream API to sort a list of integers and print only even numbers after sorting.

  9. Create a list of products with id, name, and price. Sort them in ascending order of price using lambda expressions.

  10. Write a program to sort a list of names alphabetically, ignoring case sensitivity.


Try a Short Quiz.

No quizzes available.


Go Back Top