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.



Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

How do I remove repeated elements from ArrayList?

If you don't want duplicates in a Collection, you should consider why you're using a Collection that allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList:

Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);

Of course, this destroys the ordering of the elements in the ArrayList.

Ref: https://bit.ly/3bYIjNC

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook