w3resource

Sort strings in alphabetical order using Lambda expression in Java

Java Lambda Program: Exercise-5 with Solution

Write a Java program to implement a lambda expression to sort a list of strings in alphabetical order.

Sample Solution:

Java Code:

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Create a list of strings
        List colors = Arrays.asList("red", "green", "blue", "black", "pink");

        // Print the Original list of strings
        System.out.println("Original strings:");
        for (String str : colors) {
            System.out.print(str + ' ');
        }

        // Sort the list of strings in alphabetical order using lambda expression
        colors.sort((str1, str2) -> str1.compareToIgnoreCase(str2));

        // Print the sorted list of strings
        System.out.println("\nSorted strings:");
        for (String str : colors) {
            System.out.print(str + ' ');
        }
    }
}

Sample Output:

Original strings:
red green blue black pink
Sorted strings:
black blue green pink red

Explanation:

First create a list of strings called colors using the Arrays.asList() method and print the original list elements.

To sort the strings list alphabetically, we use the sort method on the colors list. The lambda expression (str1, str2) -> str1.compareToIgnoreCase(str2) is used as a comparator. It compares two strings lexicographically, ignoring the case, using the compareToIgnoreCase method.

After sorting the list, we print the sorted list of strings.

Flowchart:

Flowchart: Java  Exercises: Check if string is empt.

Live Demo:

Java Code Editor:

Improve this sample solution and post your code through Disqus

Java Lambda Exercises Previous: Filter even and odd numbers from list using Lambda expression in Java.
Java Lambda Exercises Next: Calculate average of doubles using Lambda expression in Java.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/lambda/java-lambda-exercise-5.php