Sorting a list of strings in Java is straightforward β and you can do it in several ways, depending on whether you want natural order, reverse order, or a custom comparator.
Hereβs a complete guide π
β 1. Sort in Natural (Alphabetical) Order
import java.util.*;
public class SortStringsExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Charlie", "Alice", "Bob", "David");
// Sort alphabetically (A β Z)
Collections.sort(names);
System.out.println(names);
}
}
Output:
[Alice, Bob, Charlie, David]
β 2. Sort Using Java 8+ Streams (Functional Style)
import java.util.*;
import java.util.stream.Collectors;
public class StreamSortExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Charlie", "Alice", "Bob", "David");
List<String> sorted = names.stream()
.sorted() // natural order
.collect(Collectors.toList());
System.out.println(sorted);
}
}
π 3. Sort in Reverse Order (Z β A)
Option 1: Using Collections.sort()
Collections.sort(names, Collections.reverseOrder());
Option 2: Using Streams
List<String> sortedDesc = names.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
Output:
[David, Charlie, Bob, Alice]
π§© 4. Case-Insensitive Sorting
By default, sorting is case-sensitive β uppercase letters come before lowercase ("Zebra"
< "apple"
).
To make it case-insensitive, use a custom comparator:
List<String> names = Arrays.asList("banana", "Apple", "cherry", "apricot");
names.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(names);
Output:
[Apple, apricot, banana, cherry]
βοΈ 5. Custom Comparator (e.g., by String Length)
List<String> words = Arrays.asList("cat", "elephant", "dog", "hippopotamus");
words.sort((a, b) -> Integer.compare(a.length(), b.length()));
System.out.println(words);
Output:
[cat, dog, elephant, hippopotamus]
π§ Summary Table
Goal | Example Code |
---|---|
Alphabetical | Collections.sort(list); |
Reverse | Collections.sort(list, Collections.reverseOrder()); |
Case-insensitive | list.sort(String.CASE_INSENSITIVE_ORDER); |
By length | list.sort((a, b) -> a.length() - b.length()); |
Using streams | list.stream().sorted().collect(Collectors.toList()); |