Java List Sorting


Sorting is one of the most common operations in programming. In Java, sorting helps organize data in a particular order — either ascending or descending. When you work with lists, such as ArrayList or LinkedList, sorting helps make searching, comparisons, and data presentation easier. Java provides multiple ways to sort lists, ranging from built-in methods to custom sorting using comparators.

What is List Sorting in Java?

List sorting refers to arranging elements in a list in a defined sequence. The Java Collections Framework provides easy-to-use tools that make sorting simple and efficient. You can sort both primitive data (like numbers) and objects (like strings or user-defined classes).

The main class used for sorting in Java is Collections, which offers the sort() method. This method can automatically sort elements in ascending order if they are naturally comparable (like numbers and strings). You can also use custom comparators to define your own sorting rules.

Sorting Using Collections.sort()

The easiest way to sort a list in Java is by using Collections.sort().
Here’s how it works:

import java.util.*;

public class SortExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(45);
        numbers.add(12);
        numbers.add(78);
        numbers.add(23);

        System.out.println("Before Sorting: " + numbers);

        Collections.sort(numbers);

        System.out.println("After Sorting: " + numbers);
    }
}

Explanation:

  • The program imports the Collections class and uses the sort() method to arrange the elements in ascending order.

  • After sorting, the list [12, 23, 45, 78] is displayed.

Sorting Strings in a List

Sorting strings works in the same way. Java sorts strings alphabetically using Unicode values.

import java.util.*;

public class StringSortExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Anita");
        names.add("Meera");
        names.add("Kavya");
        names.add("Riya");

        System.out.println("Before Sorting: " + names);
        Collections.sort(names);
        System.out.println("After Sorting: " + names);
    }
}

Output:
Before Sorting: [Anita, Meera, Kavya, Riya]
After Sorting: [Anita, Kavya, Meera, Riya]

This shows alphabetical sorting by default.

Sorting in Descending Order

To sort a list in reverse order, you can use the Collections.reverseOrder() method.

import java.util.*;

public class DescendingSortExample {
    public static void main(String[] args) {
        List<Integer> marks = new ArrayList<>(Arrays.asList(89, 45, 77, 92, 60));
        System.out.println("Before Sorting: " + marks);

        Collections.sort(marks, Collections.reverseOrder());
        System.out.println("After Sorting (Descending): " + marks);
    }
}

Here, the list is sorted from highest to lowest.

Sorting Custom Objects

Sometimes, you may need to sort a list of custom objects — for example, sorting students by name or marks.
For that, you can use Comparator or Comparable.

Using Comparable

The Comparable interface allows you to define a default sorting rule inside the class itself.

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("Ananya", 85));
        list.add(new Student("Neha", 92));
        list.add(new Student("Priya", 78));

        Collections.sort(list);

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

Explanation:
The compareTo() method defines how two students are compared based on marks. The sorting happens automatically when Collections.sort() is used.

Using Comparator

A Comparator is used when you don’t want to modify the original class but still want to define custom sorting rules.

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> list = new ArrayList<>();
        list.add(new Student("Ananya", 85));
        list.add(new Student("Neha", 92));
        list.add(new Student("Priya", 78));

        Comparator<Student> sortByName = (a, b) -> a.name.compareTo(b.name);
        Collections.sort(list, sortByName);

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

Here, we’ve sorted the students alphabetically by name using a lambda expression.

Sorting with Stream API (Java 8+)

From Java 8 onwards, you can use Streams for sorting, which provides a clean and modern syntax.

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

public class StreamSortExample {
    public static void main(String[] args) {
        List<String> colors = Arrays.asList("Red", "Blue", "Green", "Yellow");

        List<String> sortedColors = colors.stream()
                                          .sorted()
                                          .collect(Collectors.toList());

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

You can also sort in reverse order:

List<String> sortedDesc = colors.stream()
                                .sorted(Comparator.reverseOrder())
                                .collect(Collectors.toList());

Why Sorting Matters

Sorting is essential in many real-world applications:

  • Sorting student records by name or marks

  • Organizing product lists by price or rating

  • Displaying leaderboards

  • Performing efficient searches (like binary search)

Efficient sorting improves the performance and readability of data-heavy applications.

Summary of the Tutorial

Sorting lists in Java is simple yet powerful. The Collections.sort() method is the most common approach, but you can also use Comparator, Comparable, or the modern Stream API for flexibility. Whether you’re sorting primitive types, strings, or custom objects, Java gives you complete control over how data is ordered. Understanding sorting helps you manage collections efficiently and present data more clearly in real-world programs.


Practice Questions

  1. Create a Java program to sort an ArrayList of integers in ascending order using Collections.sort().

  2. Write a program to sort an ArrayList of strings alphabetically and display the sorted list.

  3. Create a program to sort a list of floating-point numbers in descending order using Collections.reverseOrder().

  4. Write a program to sort a LinkedList of city names alphabetically.

  5. Create a Java program that sorts a list of student marks in ascending order, then in descending order.

  6. Write a program to sort a list of strings by their length using a Comparator.

  7. Create a program with a class Employee (name, salary). Sort the list of employees by salary using Comparable.

  8. Write a program that sorts a list of objects by multiple fields (for example, first by department, then by name).

  9. Create a Java program using Stream API to sort a list of colors alphabetically and print them.

  10. Write a program that takes user input for five numbers, stores them in an ArrayList, and sorts them in both ascending and descending order.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top