Java LinkedList sort() Method
Example
Sort a list in alphabetical order:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<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+ |
---|
More Examples
Example
Use a lambda expression to sort a list in reverse alphabetical order:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.sort( (a, b) -> { return -1 * a.compareTo(b); } );
System.out.println(cars);
}
}
Related Pages
❮ LinkedList Methods