Example 1 — Sort Numbers and Strings
Sort numbers both ways, then see how capital letters affect string order.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ArrayListSortDemo {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(Arrays.asList(42, 7, 19, 3));
nums.sort(null);
System.out.println("ascending: " + nums);
nums.sort(Comparator.reverseOrder());
System.out.println("descending: " + nums);
List<String> words = new ArrayList<>(Arrays.asList("banana", "Cherry", "apple"));
words.sort(null);
System.out.println("natural: " + words);
words.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println("ignoreCase: " + words);
}
} How It Works
- Natural order.
sort(null)usesInteger.compareTo, so the numbers go from smallest to largest. - Reverse.
Comparator.reverseOrder()flips natural order, giving largest first. - Uppercase first. Strings compare by character code, and every capital letter comes before every small letter, so "Cherry" sorts ahead of "apple".
- Ignore case.
String.CASE_INSENSITIVE_ORDERcompares the words as if they were all the same case, giving true alphabetical order.

