๐ 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 theCollections
orList
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()
Method | Available Since | Source | Notes |
---|---|---|---|
Collections.sort() | Java 1.2 | java.util.Collections | Static method, requires List as parameter |
List.sort() | Java 8 | List interface | Uses 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()
orCollections.sort()
for in-place sorting - Leverage Comparator, Lambdas, and Streams for custom sorting logic
- Use
.reversed()
,thenComparing()
, andnullsFirst()
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 :