Java tutorials > Core Java Fundamentals > Data Structures and Collections > How to sort a Collection?
How to sort a Collection?
Using Collections.sort() for List Sorting
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortList {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Charlie");
names.add("Alice");
names.add("Bob");
System.out.println("Before sorting: " + names);
Collections.sort(names);
System.out.println("After sorting: " + names);
}
}
Sorting with Comparable Interface
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Student other) {
return this.name.compareTo(other.name); // Sort by name
}
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + "}";
}
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Charlie", 20));
students.add(new Student("Alice", 22));
students.add(new Student("Bob", 21));
System.out.println("Before sorting: " + students);
Collections.sort(students);
System.out.println("After sorting: " + students);
}
}
Sorting with Comparator Interface (Custom Sorting)
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + "}";
}
}
public class SortByAge {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Charlie", 20));
students.add(new Student("Alice", 22));
students.add(new Student("Bob", 21));
System.out.println("Before sorting: " + students);
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s1.getAge() - s2.getAge(); // Sort by age
}
});
System.out.println("After sorting by age: " + students);
// Using lambda expression (Java 8 and later)
Collections.sort(students, (s1, s2) -> s1.getName().compareTo(s2.getName()));
System.out.println("After sorting by name using lambda: " + students);
}
}
Concepts Behind the Snippet
Real-Life Use Case
Best Practices
Interview Tip
When to Use Them
Memory Footprint
Alternatives
Pros and Cons of `Comparable` vs. `Comparator`
`Comparator`
FAQ
-
How do I sort a list in descending order?
You can use `Collections.reverseOrder()` in conjunction with `Collections.sort()` to sort in descending order. Alternatively, you can use `Comparator.reverseOrder()` with a custom comparator. For example: `Collections.sort(myList, Collections.reverseOrder());` or implement your custom comparator by inversing the logic. -
What happens if I try to sort a list containing null values?
Attempting to sort a list containing null values without handling them will typically result in a `NullPointerException`. You need to handle nulls in your `compareTo()` or `compare()` method. For example, you might treat nulls as either the smallest or largest values. -
How can I sort a list of custom objects based on multiple fields?
You can create a `Comparator` that compares objects based on multiple fields. You can chain comparisons using `thenComparing()` or `thenComparingInt()`, `thenComparingDouble()`, etc. For example:
Comparator.comparing(Student::getLastName).thenComparing(Student::getFirstName)
-
What is the time complexity of `Collections.sort()`?
The time complexity of `Collections.sort()` for `List` implementations (like `ArrayList`) is typically O(n log n), where n is the number of elements in the list. This is because it uses a variant of merge sort, which provides good performance in most cases.