Write a Java program using Lambda Expression to find the minimum string in a list of strings


The java program that finds the minimum (shortest) string from a list of strings using Java Streams and a lambda expression. Here's an explanation of the code:

  • The Minimum_String class is defined, which contains the main method, where the program's execution begins.
  • Inside the main method:
    • A list of strings named strings is created using an ArrayList, and several strings are added to it.
    • String minString = strings.stream().min((str1, str2) -> Integer.compare(str1.length(), str2.length())).orElse(null);: This line uses a stream to find the minimum string from the strings list based on the length of the strings. It uses the min operation and provides a lambda expression (str1, str2) -> Integer.compare(str1.length(), str2.length()) as a comparator. This comparator compares the lengths of two strings and returns the one with the shorter length as the minimum string. The orElse(null) part ensures that if there are no strings in the list, it returns null.
    • System.out.println("List of Strings : " + strings);: This line prints the list of strings.
    • System.out.println("Minimum String : " + minString);: This line prints the minimum (shortest) string found in the list.

Source Code

import java.util.ArrayList;
import java.util.List;
 
public class Minimum_String
{
	public static void main(String[] args)
	{
		// Create a list of strings
		List<String> strings = new ArrayList<>();
		strings.add("Blueberry");
		strings.add("Banana");
		strings.add("Apple");
		strings.add("Grapes");
		strings.add("Pineapple");
 
		// Find the minimum string using a lambda expression
		String minString = strings.stream().min((str1, str2) -> Integer.compare(str1.length(), str2.length())).orElse(null);
 
		// Print the list of strings and the minimum string
		System.out.println("List of Strings : " + strings);
		System.out.println("Minimum String : " + minString);
	}
}

Output

List of Strings : [Blueberry, Banana, Apple, Grapes, Pineapple]
Minimum String : Apple

Example Programs