This is the second solution to check whether a given string is palindrome or not. This approach uses a simple predicate with lambda expression, and uses String class methods.
import java.util.Scanner;
import java.util.function.Predicate;
public class PalindromeCheck {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner inpStringVar = new Scanner(System.in);
/* Define a Predicate to check whether String is Palindrome using Lambda
* expression */
Predicate<String> palinStr = (strVal) -> {
int strLen = strVal.length();
String revStr = new String("");
while (--strLen >= 0)
revStr += strVal.charAt(strLen);
return (strVal.equalsIgnoreCase(revStr));
};
/* Input a string here */
System.out.print("Enter String or Alpha numeric value: ");
String inpStr = inpStringVar.next();
System.out.println("The string: " + inpStr + " is Palindrome (True/False): " + palinStr.test(inpStr));
}
}
Output:
Enter String or Alpha numeric value: Sanjay
The string: Sanjay is Palindrome (True/False): false

Leave a comment