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


The Java program finds the smallest palindrome string from a list of strings using Java Streams. Here's how the program works:

  • An ArrayList named strings is created to store a list of strings.
  • System.out.println("Given String : " + strings); prints the original list of strings.
  • The program uses Java Streams to find the smallest palindrome string:
    • strings.stream(): This converts the strings list into a stream of strings.
    • .filter(SmallestPalindromeString::isPalindrome): This filters the stream to keep only the palindrome strings. It uses the isPalindrome method as a predicate to check if a string is a palindrome. The :: operator is used to reference the static method isPalindrome defined in the SmallestPalindromeString class.
    • .min((str1, str2) -^gt; Integer.compare(str1.length(), str2.length())): This finds the smallest palindrome string by comparing their lengths. The min function compares the lengths of the strings using a custom comparator. It selects the string with the smallest length.
    • .orElse("No palindrome found"): This part handles the case when there are no palindrome strings in the list. If there are no palindromes, it returns the default message "No palindrome found."
  • The program stores the result in the smallestPalindrome variable.
  • It then uses System.out.println("Smallest Palindrome String : " + smallestPalindrome); to print the smallest palindrome string or "No palindrome found" if no palindromes are found.

Source Code

import java.util.ArrayList;
import java.util.List;
 
public class SmallestPalindromeString
{
	public static void main(String[] args)
	{
		List<String> strings = new ArrayList<>();
		strings.add("hello");
		strings.add("deified");
		strings.add("java");
		strings.add("deed");
		strings.add("level");
 
		System.out.println("Given String : " + strings);
 
		// Using Lambda Expression to find the smallest palindrome string
		String smallestPalindrome = strings.stream()
			.filter(SmallestPalindromeString::isPalindrome) // Filter palindrome strings
			.min((str1, str2) -> Integer.compare(str1.length(), str2.length())) // Find the smallest one
			.orElse("No palindrome found"); // Handle case when there are no palindromes
 
		System.out.println("Smallest Palindrome String : " + smallestPalindrome);
	}
 
	// Helper method to check if a string is a palindrome
	public static boolean isPalindrome(String str)
	{
		String reversed = new StringBuilder(str).reverse().toString();
		return str.equals(reversed);
	}
}

Output

Given String : [hello, deified, java, deed, level]
Smallest Palindrome String : deed

Example Programs