ArrayList sort() method - Syntax and Examples
Learn how to use the Java ArrayList `sort()` method with a custom Comparator. This tutorial explains the syntax, parameters, return values, and provides practical examples.
This reference explains ArrayList sort() method - Syntax and Examples through its syntax, examples and boundaries. Use the linked course lessons when the surrounding Java concepts are unfamiliar.
Use this reference
Identify the documented behavior, read a complete example and check its inputs before applying it.
ArrayList sort() method - Syntax and Examples
Introduction
The `sort()` method in Java's ArrayList allows you to sort the elements within the list based on a custom comparison logic. You provide a Comparator object that dictates how two elements should be compared, giving you fine-grained control over the sorting process. This is particularly useful when dealing with objects or data types where the default natural ordering might not suffice.
Syntax
public void sort(Comparator<? super E> c)
Parameters
| Parameter | Description |
|---|---|
c |
The Comparator object that defines the order of elements in the list. If null, the list is sorted according to its natural ordering (if the elements implement the Comparable interface). |
Return Value
This method doesn't return any value; it sorts the ArrayList in place. It is a void method.
Examples
Sorting ArrayList of Strings by Length
In this example, we sort an ArrayList of strings based on their lengths. We create a Comparator that compares two strings and returns a negative number if the first string is shorter than the second, a positive number if it's longer, and zero if they have equal length.
import java.util.*;
public class SortByLength {
public static void main(String[] args) {
ArrayList<String> strings = new ArrayList<>(
Arrays.asList("apple", "banana", "kiwi", "orange"));
strings.sort((s1, s2) -> Integer.compare(s1.length(), s2.length()));
System.out.println(strings);
}
}
[kiwi, apple, orange, banana]
Explanation: The lambda expression (s1, s2) -> Integer.compare(s1.length(), s2.length()) acts as a Comparator. It compares the lengths of two strings (s1 and s2) using Integer.compare(). The resulting ArrayList is sorted in ascending order based on string length.
Sorting ArrayList of Integers in Descending Order
This example demonstrates sorting an ArrayList of integers in descending order. We create a Comparator that subtracts the second integer from the first, effectively reversing their natural ordering.
import java.util.*;
public class SortDescending {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>(
Arrays.asList(5, 2, 8, 1, 9));
numbers.sort((a, b) -> Integer.compare(b, a)); // or (a, b) -> -Integer.compare(a, b)
System.out.println(numbers);
}
}
[9, 8, 5, 2, 1]
Explanation: The lambda expression (a, b) -> Integer.compare(b, a) defines the Comparator. By subtracting 'a' from 'b', we reverse the natural order of integers, resulting in descending sort.
Sorting ArrayList of Custom Objects
This example showcases sorting an ArrayList of custom objects (Person in this case) based on their age. We create a Comparator class that compares two Person objects and returns a value indicating their relative order.
import java.util.*;
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{ name="" + name + "", age="" + age + ""}";
}
}
public class SortByAge {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<>(
Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
));
people.sort(Comparator.comparingInt(Person::age));
System.out.println(people);
}
}
[Person{ name='Bob', age=25 }, Person{ name='Alice', age=30 }, Person{ name='Charlie', age=35 }]
Explanation: The Comparator.comparingInt(Person::age) creates a comparator that sorts the list of people based on their age. The lambda expression is replaced with this concise method call.
Using this reference
Check the example’s types, inputs and documented behavior before copying it into an application. Some APIs require external libraries, files or platform services; consult their setup notes.
Related explanations: Java Data Types - Primitive and Non-Primitive, Java Class - Blueprint of Objects, Exceptions in Java Introduction.
Supporting documentation: Official Java learning guide.
Reference checks are optional and do not count toward course progress.