list of strings

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

GoalExample Code
AlphabeticalCollections.sort(list);
ReverseCollections.sort(list, Collections.reverseOrder());
Case-insensitivelist.sort(String.CASE_INSENSITIVE_ORDER);
By lengthlist.sort((a, b) -> a.length() - b.length());
Using streamslist.stream().sorted().collect(Collectors.toList());

Leave a Reply