How to sort a List/ArrayList?
How do you sort a List or ArrayList in Java? What are the common methods to arrange elements in ascending or custom order efficiently?
Sorting a List or ArrayList in Java is a common task and can be done easily using built-in methods provided by the Java Collections Framework. Whether you want to sort numbers, strings, or custom objects, Java has you covered.
How to sort a List/ArrayList?
Using Collections.sort():
The simplest way to sort a List or ArrayList is by using the static method Collections.sort().
List numbers = new ArrayList<>(Arrays.asList(5, 3, 8, 1));
Collections.sort(numbers);
System.out.println(numbers); // Output: [1, 3, 5, 8]
This sorts the list in ascending order according to the natural ordering of the elements (e.g., numbers from smallest to largest).
Sorting custom objects:
If you have a list of custom objects, you need to either make your class implement the Comparable interface or provide a Comparator.
class Person implements Comparable {
String name;
int age;
public int compareTo(Person other) {
return this.age - other.age; // Sort by age ascending
}
}
Or use a Comparator:
Collections.sort(personList, (p1, p2) -> p1.getName().compareTo(p2.getName()));
Using Java 8+ Streams:
You can also sort using streams and get a sorted list:
List sortedNumbers = numbers.stream()
.sorted()
.collect(Collectors.toList());
Summary:
- Use Collections.sort() for simple sorting.
- Implement Comparable or use Comparator for custom sorting logic.
- Java 8 streams provide a modern and flexible way to sort.
- Sorting changes the order of elements in the list or creates a new sorted collection.
Sorting lists is straightforward in Java, and with these tools, you can sort almost anything quickly and cleanly!