๐Ÿ“Š Java Data Structures
Estimated reading: 4 minutes 37 views

๐Ÿ“Š Java List Sorting โ€“ Complete Guide with Syntax, Comparators & Best Practices


๐Ÿงฒ Introduction โ€“ Why List Sorting Matters in Java

Whether you’re building a shopping cart, leaderboard, or contact list โ€” sorting is essential. Java offers multiple ways to sort a list using built-in methods and custom logic for advanced ordering.

With the power of the Collections Framework, Lambdas, and Comparators, Java makes it easy to sort lists by names, numbers, dates, or even complex objects.

By the end of this guide, you’ll learn:

โœ… How to sort a Java List in ascending and descending order
โœ… How to use Collections.sort() and List.sort()
โœ… How to sort custom objects with Comparator and Lambdas
โœ… Performance tips and best practices


๐Ÿ”‘ What Is List Sorting in Java?

๐Ÿ“Š Sorting a List in Java means arranging its elements in a specific order (natural or custom), using utilities from the Collections or List interface.


๐Ÿงช 1. Sorting a List of Strings

import java.util.*;

public class SortStrings {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("John", "Alice", "Bob");
        Collections.sort(names); // Ascending
        System.out.println(names); // [Alice, Bob, John]
    }
}

โœ… Collections.sort() sorts the list in natural (alphabetical) order


๐Ÿ”„ Descending Order

names.sort(Collections.reverseOrder());
System.out.println(names); // [John, Bob, Alice]

โœ… Use reverseOrder() for descending sort


๐Ÿ”ข 2. Sorting a List of Integers

List<Integer> numbers = Arrays.asList(5, 1, 3, 9);
Collections.sort(numbers);
System.out.println(numbers); // [1, 3, 5, 9]

๐Ÿ“˜ Java uses natural order (ascending) for numbers


๐Ÿงฑ 3. Sorting Custom Objects (e.g., Students)

๐Ÿงฉ Using Comparator Class

class Student {
    String name;
    int age;

    Student(String n, int a) {
        name = n;
        age = a;
    }

    public String toString() {
        return name + " (" + age + ")";
    }
}
List<Student> list = new ArrayList<>();
list.add(new Student("Ravi", 23));
list.add(new Student("Aman", 21));
list.add(new Student("Sneha", 22));

// Sort by age
list.sort(Comparator.comparingInt(s -> s.age));
System.out.println(list); // [Aman (21), Sneha (22), Ravi (23)]

โœ… Comparator.comparingInt() is concise and readable
โœ… You can also use Collections.sort(list, comparator)


๐Ÿง  Sort by Name (String Field)

list.sort(Comparator.comparing(s -> s.name));

โœ… Alphabetical sorting by name using Lambda


๐Ÿ” Sort in Descending Order

list.sort(Comparator.comparingInt((Student s) -> s.age).reversed());

โœ… Add .reversed() to any comparator


๐Ÿ“ฆ Collections.sort() vs List.sort()

MethodAvailable SinceSourceNotes
Collections.sort()Java 1.2java.util.CollectionsStatic method, requires List as parameter
List.sort()Java 8List interfaceUses lambda, cleaner, more modern

๐Ÿงช 4. Sorting with Streams (Java 8+)

list.stream()
    .sorted(Comparator.comparing(s -> s.name))
    .forEach(System.out::println);

โœ… Non-destructive sort โ€” use when you don’t want to modify original list


๐Ÿ“˜ Real-World Use Case: Sorting Products by Price

class Product {
    String name;
    double price;

    Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String toString() {
        return name + ": $" + price;
    }
}

List<Product> products = Arrays.asList(
    new Product("Phone", 799.99),
    new Product("Laptop", 1200.0),
    new Product("Tablet", 450.0)
);

products.sort(Comparator.comparingDouble(p -> p.price));
System.out.println(products);

โœ… Sorts the product list by price in ascending order


๐Ÿ’ก Best Practices for List Sorting

โœ… Use Comparator.comparing() and Lambdas for cleaner code
โœ… Prefer List.sort() for modern Java (Java 8+)
โœ… Use .reversed() to flip sorting order
โœ… Use stream().sorted() for non-destructive sorting
โœ… Avoid null values unless explicitly handled in comparator


โœ… Summary

  • Java provides powerful tools to sort any type of List
  • Use List.sort() or Collections.sort() for in-place sorting
  • Leverage Comparator, Lambdas, and Streams for custom sorting logic
  • Use .reversed(), thenComparing(), and nullsFirst() for advanced control

โ“ FAQs โ€“ Java List Sorting

โ“ How do I sort a list in descending order?

Use .sort(Collections.reverseOrder()) or Comparator.reversed()

โ“ What if the list contains null values?

Use a comparator like:

Comparator.nullsLast(Comparator.comparing(...))

โ“ Can I sort by multiple fields?

Yes. Use thenComparing():

list.sort(Comparator.comparing(Student::getAge).thenComparing(Student::getName));

โ“ Does sorting modify the original list?

Yes โ€” Collections.sort() and List.sort() sort in place.
Use Streams if you want to keep the original list unchanged.

โ“ What is the default sort order?

Java sorts strings alphabetically and numbers ascendingly by default.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Java List Sorting

Or Copy Link

CONTENTS
Scroll to Top