Flash cards
Review the key moves
What is the main idea behind Java ArrayList sort() Method?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ java.util.ArrayList;Put the learning moves in the order that makes the concept easiest to apply.
❮ ArrayList Methods
Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.sort(null);
System.out.println(cars);
}
}Definition and Usage
The sort() method sorts items in the list. A Comparator can be used to compare pairs of elements. The comparator can be defined by a lambda expression which is compatible with the compare() method of Java's Comparator interface.
If null is passed into the method then items will be sorted naturally based on their data type (e.g. alphabetically for strings, numerically for numbers). Non-primitive types must implement Java's Comparable interface in order to be sorted without a comparator.
Syntax
public void sort(Comparator
compare )Parameter Values
| Parameter | Description |
|---|---|
| compare | Required. A comparator or lambda expression which compares pairs of items in the list. Pass null to compare items naturally by their data type. |
Technical Details
| Java version: | 1.8+ |
|---|