Quick Answer
Order collections in Java.
Understanding the Issue
Java provides multiple ways to sort lists using Comparator and natural ordering.
The Problem
This code demonstrates the issue:
Java
Error
List<String> names = Arrays.asList("Bob", "Alice", "Charlie");
The Solution
Here's the corrected code:
Java
Fixed
// Natural order:
Collections.sort(names);
// Custom comparator:
names.sort(Comparator.comparing(String::length));
// Reverse order:
names.sort(Comparator.reverseOrder());
// Java 8+ syntax:
names.sort((a, b) -> a.compareTo(b));
// Object sorting:
persons.sort(Comparator
.comparing(Person::getLastName)
.thenComparing(Person::getAge));
Key Takeaways
Use Comparator for flexible sorting criteria.