w3resource

Sort strings in alphabetical order using Lambda expression in Java


Sort List of Strings in Alphabetical Order

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.

For more Practice: Solve these Related Problems:

  • Write a Java program to implement a lambda expression that sorts a list of strings in reverse alphabetical order.
  • Write a Java program to create a lambda that sorts a list of strings by length and then alphabetically for equal lengths.
  • Write a Java program to implement a lambda expression that sorts strings ignoring case sensitivity.
  • Write a Java program to chain lambda expressions to sort a list of strings and then filter out those starting with a specific letter.

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.



Follow us on Facebook and Twitter for latest update.