Write a Java program using Lambda Expression to find the longest palindrome string in a list of strings
The java program that finds the longest palindrome in a list of strings using Java Streams. Here's an explanation of the code:
- An ArrayList named strings is created to store a list of strings. Some of the strings in the list are palindromes, and some are not.
- System.out.println("Given String : " + strings); prints the original list of strings.
- The program uses Java Streams to filter and find the longest palindrome:
- strings.stream(): This converts the strings list into a stream of strings.
- .filter(s -> s.equalsIgnoreCase(new StringBuilder(s).reverse().toString())): This is a filter operation that retains only the strings in the stream that are palindromes. It checks if a string, when converted to lowercase and compared with its reverse, remains the same. This filter condition is case-insensitive.
- .max((s1, s2) -> s1.length() - s2.length()): This is a max operation that finds the longest palindrome in the stream based on the length of the strings. It uses a lambda expression to compare the lengths of two strings and select the one with the maximum length.
- .orElse("No palindrome found"): This specifies a default value to return if no palindrome is found in the stream.
- System.out.println("Longest Palindrome : " + longest_palindrome); prints the longest palindrome found or the default message if no palindrome is found.
Source Code
import java.util.ArrayList;
import java.util.List;
public class LongestPalindrome
{
public static void main(String[] args)
{
List<String> strings = new ArrayList<>();
strings.add("java");
strings.add("racecar");
strings.add("level");
strings.add("deified");
System.out.println("Given String : " + strings);
String longest_palindrome = strings.stream().filter(s -> s.equalsIgnoreCase(new StringBuilder(s).reverse().toString())).max((s1, s2) -> s1.length() - s2.length()).orElse("No palindrome found");
System.out.println("Longest Palindrome : " + longest_palindrome);
}
}
Output
Given String : [java, racecar, level, deified]
Longest Palindrome : racecar