Java 8 Program to Sort List of Strings Alphabetically

1. Introduction

Sorting a list of strings alphabetically is a fundamental task in programming, often required for data processing and management. With the advent of Java 8, the Stream API has provided a more intuitive and efficient way to handle such operations. This blog post will demonstrate how to alphabetically sort a list of strings using Java 8 Streams, showcasing the simplicity and power of functional programming in Java.

2. Program Steps

1. Create a list of strings.

2. Use Java 8 Streams to sort the list alphabetically.

3. Collect the sorted results back into a list.

4. Display the sorted list.

3. Code Program

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SortStringsAlphabetically {
    public static void main(String[] args) {
        // Creating a list of strings
        List<String> strings = Arrays.asList("Banana", "Apple", "Orange", "Mango", "Grape");

        // Using Java 8 Streams to sort the list alphabetically
        List<String> sortedStrings = strings.stream() // Converting the list to a stream
                                             .sorted() // Sorting the stream alphabetically
                                             .collect(Collectors.toList()); // Collecting the sorted stream back into a list

        // Displaying the sorted list
        System.out.println("Sorted list of strings:");
        sortedStrings.forEach(System.out::println); // Printing each element of the sorted list
    }
}

Output:

Sorted list of strings:
Apple
Banana
Grape
Mango
Orange

Explanation:

1. The program starts by importing the necessary classes. Arrays and List from the java.util package are used to create and manage the list of strings, and Collectors from the java.util.stream package is used for collecting stream results.

2. A list named strings is initialized with an array of string values. The list contains names of fruits in an unsorted order.

3. To sort the list alphabetically, the stream() method is used to convert the list into a stream of strings. The sorted() method is then applied to the stream, which sorts the elements according to their natural order (alphabetically in this case for strings).

4. The sorted stream is collected back into a new list called sortedStrings using the collect(Collectors.toList()) terminal operation. This step is crucial for converting the stream back into a list after sorting.

5. Finally, the program iterates over the sortedStrings list using the forEach method and prints each string to the console. The method reference System.out::println is used to pass each element of the list to the println method.

6. This approach illustrates how Java 8 Streams facilitate easy sorting of collections with minimal code, highlighting the benefits of functional programming in Java.

Comments