write a Java program using Lambda Expression to sort the strings based on their lengths in ascending order
The java program that sorts a list of strings in ascending order based on their lengths using a lambda expression and the Collections.sort method. Here's an explanation of the code:
- import java.util.ArrayList;: This line imports the ArrayList class from the java.util package, which is used to create an ArrayList to store strings.
- import java.util.Collections;: This line imports the Collections class, which provides utility methods for working with collections, including sorting.
- The StringSort class is defined, which contains the main method, where the program's execution begins.
- Inside the main method:
- List strings = new ArrayList<>(List.of("Pineapple", "Apple", "Banana", "Orange", "Raspberries", "Grape", "Blueberry"));: This line creates an ArrayList named strings and initializes it with a list of strings. The List.of method is used to create an immutable list, which is then copied to an ArrayList.
- System.out.println("Given String : " + strings); : This line prints the original list of strings.
- Collections.sort(strings, (s1, s2) -> s1.length() - s2.length());: This line uses the Collections.sort method to sort the strings list in ascending order based on the length of the strings. It uses a lambda expression (s1, s2) -> s1.length() - s2.length() as a comparator to compare the lengths of the strings. The sort method will rearrange the elements of the list accordingly.
- System.out.println("Ascending Order : " + strings);: This line prints the list of strings in ascending order of their lengths.
Source Code
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StringSort
{
public static void main(String[] args)
{
List<String> strings = new ArrayList<>(List.of("Pineapple", "Apple", "Banana", "Orange", "Raspberries", "Grape", "Blueberry"));
System.out.println("Given String : "+strings);
Collections.sort(strings, (s1, s2) -> s1.length() - s2.length());
System.out.println("Ascending Order : "+strings);
}
}
Output
Given String : [Pineapple, Apple, Banana, Orange, Raspberries, Grape, Blueberry]
Ascending Order : [Apple, Grape, Banana, Orange, Pineapple, Blueberry, Raspberries]