Write a Java program using Lambda Expression to check if a given string is a palindrome (reads the same backward as forward), ignoring spaces and case
The java program that checks whether a given string is a palindrome using a lambda expression and a custom functional interface StringChecker. Here's an explanation of the code:
- The Palindrome class is defined, which contains the main method, where the program's execution begins.
- Inside the main method:
- StringChecker isPalindromeLambda = str -> { ... };: This line defines a lambda expression using the StringChecker functional interface. The lambda expression checks whether a given string is a palindrome. It does so by first removing whitespace and converting the string to lowercase. Then, it compares the cleaned string with its reverse to determine if it's a palindrome.
- System.out.println("rotator is Palindrome : " + isPalindromeLambda.check("rotator"));: This line uses the isPalindromeLambda lambda expression to check if the string "rotator" is a palindrome and prints the result.
- System.out.println("world is Palindrome : " + isPalindromeLambda.check("world"));: This line uses the isPalindromeLambda lambda expression to check if the string "world" is a palindrome and prints the result.
- The StringChecker functional interface is defined, which declares a single method named check that takes a string and returns a boolean. This interface is used to define the lambda expression for checking palindromes.
Source Code
public class Palindrome
{
public static void main(String[] args)
{
StringChecker isPalindromeLambda = str -> {
String cleanedStr = str.replaceAll("\\s", "").toLowerCase();
return cleanedStr.equals(new StringBuilder(cleanedStr).reverse().toString());
};
System.out.println("rotator is Palindrome : "+isPalindromeLambda.check("rotator"));
System.out.println("world is Palindrome : "+isPalindromeLambda.check("world"));
}
}
interface StringChecker
{
boolean check(String str);
}
Output
rotator is Palindrome : true
world is Palindrome : false