Write a Java program using Lambda Expression to sort a list of strings in alphabetical order


The java program that sorts a list of strings in a case-insensitive manner using a lambda expression. Here's an explanation of the code:

  • import java.util.Arrays;: This line imports the Arrays class from the java.util package, which is used to create a list of strings from an array.
  • import java.util.List;: This line imports the List class from the java.util package, which is used to work with lists.
  • The SortList class is defined, which contains the main method, where the program's execution begins.
  • Inside the main method:
    • List<String> str = Arrays.asList("Mango", "Cherry", "Apple", "Banana");: This line creates a list of strings named str containing the elements "Mango," "Cherry," "Apple," and "Banana."
    • System.out.println("Original Strings : " + str); : This line prints the original list of strings.
    • str.sort((s1, s2) -> s1.compareToIgnoreCase(s2)); : This line uses the sort method to sort the str list of strings. The lambda expression (s1, s2) -> s1.compareToIgnoreCase(s2) is used as a comparator to sort the strings in a case-insensitive manner. It compares the strings using the compareToIgnoreCase method, which compares strings while ignoring the case.
    • System.out.println("Sorted Strings : " + str); : This line prints the list of strings after sorting.

Source Code

import java.util.Arrays;
import java.util.List;
 
public class SortList
{
	public static void main(String[] args)
	{
		List<String> str = Arrays.asList("Mango", "Cherry", "Apple", "Banana");
		System.out.println("Original Strings : " + str);
 
		str.sort((s1, s2) -> s1.compareToIgnoreCase(s2));
 
		System.out.println("Sorted Strings : " + str);
	}
}

Output

Original Strings : [Mango, Cherry, Apple, Banana]
Sorted Strings : [Apple, Banana, Cherry, Mango]

Example Programs