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


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

  • The Maximum_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 maxString = strings.stream().max((str1, str2) -> Integer.compare(str1.length(), str2.length())).orElse(null);: This line uses a stream to find the maximum string from the strings list based on the length of the strings. It uses the max 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 greater length as the maximum 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("Maximum String : " + maxString);: This line prints the maximum (longest) string found in the list.

Source Code

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

Output

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

Example Programs