Back to Java
2026-01-216 min read

Sort List (Java)

Learn Sort List (Java) step by step with clear examples and exercises.

Title: A full guide to Sorting a List in Java - From Basics to Advanced Techniques

Why This Matters

Sorting is a fundamental concept in computer science, playing an essential role in managing data efficiently and optimizing search algorithms. In real-world scenarios, sorting is crucial for maintaining order in large datasets, managing databases, and ensuring the smooth functioning of various applications. In Java interviews, you may encounter questions about various sorting algorithms to demonstrate your problem-solving skills.

Prerequisites

To fully grasp this lesson, you should be familiar with:

  1. Basic Java syntax (variables, methods, loops, and control structures)
  2. Arrays in Java
  3. Concept of Big O notation for time complexity analysis
  4. Understanding of Object-Oriented Programming (OOP) principles, such as classes, objects, inheritance, interfaces, and exception handling
  5. Knowledge of recursion and its applications
  6. Familiarity with the Java Collections Framework, including List, ArrayList, LinkedList, and others

Core Concept

In Java, we can sort lists using built-in sorting algorithms like Collections.sort(), Arrays.sort(), or implementing custom sorting algorithms such as QuickSort, MergeSort, HeapSort, and BubbleSort. This lesson will cover the usage of Collections.sort() and provide a more in-depth look at its implementation and various applications.

The Collections.sort() Method

The Collections.sort() method is a static utility function in Java's java.util package that sorts a list or array of objects implementing the Comparable interface. It works by using a merge sort algorithm internally but can be optimized for better performance when dealing with specific data types.

Here's an example of how to use the Collections.sort() method:

import java.util.*;

public class SortListExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 2, 6, 3, 1);
Collections.sort(numbers);
System.out.println(numbers); // Output: [1, 2, 3, 5, 6]
}
}

Customizing the Sorting Algorithm with Comparator

By default, Collections.sort() sorts lists based on their natural order (ascending for objects and lexicographic for strings). However, you can customize the sorting algorithm by providing a Comparator object that defines your own comparison logic.

import java.util.*;

public class CustomComparatorExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave", "Eve");
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return b.compareToIgnoreCase(a); // Sort in reverse order
}
});
System.out.println(names); // Output: [Eve, Dave, Charlie, Bob, Alice]
}
}

Time Complexity Analysis

The time complexity of the Collections.sort() method is O(n log n) in the average and worst cases, making it an efficient sorting algorithm for large datasets. However, keep in mind that creating a copy of the list internally during the sorting process may consume additional memory if the original list is large.

Worked Example

Let's dive into a worked example to better understand how the Collections.sort() method works:

import java.util.*;

public class SortListExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave", "Eve");
System.out.println("Unsorted: " + names); // Output: [Alice, Bob, Charlie, Dave, Eve]

Collections.sort(names);
System.out.println("Sorted (default): " + names); // Output: [Alice, Bob, Charlie, Dave, Eve]

Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return b.compareToIgnoreCase(a); // Sort in reverse order
}
});
System.out.println("Sorted (reverse): " + names); // Output: [Eve, Dave, Charlie, Bob, Alice]
}
}

Line-by-Line Explanation

  1. Import the Collections class from the java.util package.
  2. Declare a list of strings called names.
  3. Print the unsorted list to the console for reference.
  4. Call the Collections.sort() method on the names list and pass it as an argument to sort in default (ascending) order.
  5. Print the sorted list to the console to verify that it has been correctly sorted in ascending order.
  6. Create a custom Comparator object that sorts strings in reverse order using the compareToIgnoreCase() method.
  7. Call the Collections.sort() method again, passing both the names list and the custom comparator as arguments to sort the list in reverse order.
  8. Print the sorted list to the console to verify that it has been correctly sorted in reverse order.

Common Mistakes

  1. Not importing the Collections class: Remember to include the line import java.util.Collections; at the beginning of your code.
  2. Using the wrong data type: The Collections.sort() method only works with objects implementing the Comparable interface or when provided with a custom Comparator.
  3. Sorting lists within loops: Avoid sorting lists within loops as it can lead to performance issues due to the repeated copying of the list during each iteration.
  4. Not understanding Big O notation: Familiarize yourself with Big O notation to understand the time complexity of sorting algorithms and make informed decisions about which algorithm to use in different scenarios.
  5. Misusing the Comparator interface: Make sure you correctly implement the compare() method in your custom comparators, and remember that they must adhere to the contract defined by the Comparator interface.
  6. Not handling null values: If your list contains null values, you may need to handle them appropriately when sorting or using a custom comparator that can compare them effectively.
  7. Using Arrays.sort() instead of Collections.sort() for lists: Be aware that the Arrays.sort() method is intended for arrays, while Collections.sort() is designed for lists.

Practice Questions

  1. Write a Java program that sorts an ArrayList of integers using the Collections.sort() method and calculates the sum of all even numbers.
  2. Implement a custom sorting algorithm called QuickSort for an ArrayList of strings, and use it to sort a list of names in alphabetical order.
  3. Given an ArrayList of integers, write a Java program that finds the smallest range between two consecutive elements with the maximum difference.
  4. Create a custom comparator for sorting an ArrayList of Employee objects based on their salary (assuming you have a class called Employee with properties like name and salary).
  5. Write a Java program that sorts an ArrayList of Customers (assuming you have a class called Customer with properties like name, age, and balance) in descending order by balance, then by age, and finally by name.
  6. Implement a custom sorting algorithm called MergeSort for an ArrayList of integers and compare its performance with the built-in Collections.sort() method.
  7. Write a Java program that sorts an ArrayList of Customers using both QuickSort and MergeSort algorithms, and compare their time complexities and efficiency in different scenarios.

FAQ

  1. Can I customize the sorting algorithm used by Collections.sort()? Yes, you can provide a custom Comparator to Collections.sort() to define your own comparison logic.
  2. What is the time complexity of BubbleSort compared to QuickSort and MergeSort? The time complexity of BubbleSort is O(n^2) in the worst case, while QuickSort and MergeSort both have a time complexity of O(n log n). However, BubbleSort has the advantage of being simpler and more intuitive.
  3. Why does Collections.sort() create a copy of the list during sorting? Creating a copy of the list allows the original list to remain unmodified while the sort operation is performed on the copy. This ensures that the original data remains intact in case of unexpected errors or if the sort operation needs to be interrupted.
  4. Is it possible to use Collections.sort() with arrays? No, Collections.sort() is intended for lists only. For arrays, you can use the Arrays.sort() method instead.
  5. What happens if I sort an empty list using Collections.sort()? Sorting an empty list does not cause any errors but will simply return without modifying the list since it has no elements to sort.
  6. Can I use both Comparable and Comparator interfaces together for my custom class? Yes, you can implement both the Comparable and Comparator interfaces for your custom class. However, be aware that using both may lead to confusion about which comparison logic will be used in different scenarios. It is generally recommended to stick with one or the other.
Sort List (Java) | Java | XQA Learn