Java List Sorting: How to Sort ArrayLists and LinkedLists
Learn how to sort Java lists such as ArrayList and LinkedList using the Collections class from the java.util package. Discover methods to sort elements, including sorting an ArrayList of Strings in ascending alphabetical order, and improve data organization in Java applications.
Java List Sorting
In Java, you can sort lists like ArrayList and LinkedList using the Collections
class from the java.util package.
Sort an ArrayList
To sort an ArrayList of Strings alphabetically in ascending order:
Syntax
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Collections.sort(cars); // Sort cars
for (String i : cars) {
System.out.println(i);
}
}
}
Output
Output
BMW
Ford
Mazda
Volvo
To sort an ArrayList of Integers numerically in ascending order:
Syntax
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<>();
myNumbers.add(33);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(34);
myNumbers.add(8);
myNumbers.add(12);
Collections.sort(myNumbers); // Sort myNumbers
for (int i : myNumbers) {
System.out.println(i);
}
}
}
Output
Output
8
12
15
20
33
34
Reverse the Order
To sort a list in reverse order, use the Collections.reverseOrder()
method:
Sorting an ArrayList of Strings in reverse/descending order:
Syntax
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Collections.sort(cars, Collections.reverseOrder()); // Sort cars in reverse order
for (String i : cars) {
System.out.println(i);
}
}
}
Output
Output
Volvo
Mazda
Ford
BMW
Sorting an ArrayList of Integers in reverse/descending order:
Syntax
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<>();
myNumbers.add(33);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(34);
myNumbers.add(8);
myNumbers.add(12);
Collections.sort(myNumbers, Collections.reverseOrder()); // Sort myNumbers in reverse order
for (int i : myNumbers) {
System.out.println(i);
}
}
}
Output
Output
34
33
20
15
12
8