Learn how to find palindrome strings in array using Java 8 Stream API.A palindrome string reads the same forward and backward, such as “radar” and “madam”.
Code Explanation (Step-by-Step) :
- Create an array containing multiple string values.
- Convert the array into a List using Arrays.asList() .
- Convert the list into a stream using stream() .
- Use the filter() method to identify palindrome strings.
- Reverse each string using StringBuilder.reverse().
- str.equals() method to compare the original string with the reversed string.
- collect(Collectors.toList()) method to collect all palindrome strings
- Print the resulting palindrome strings.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class PalindromeTest {
public static void main(String[] args) {
String[] arr = {"spring", "radar", "java", "try", "madam"};
List list = Arrays.asList(arr);
List palindromeString = list.stream()
.filter(str -> str.equals(new StringBuilder(str).reverse().toString()))
.collect(Collectors.toList());
System.out.println("Print all the palindrome strings are: " + palindromeString);
}
}
Output :-
Print all the palindromes string are :- [radar, madam]
What is a Palindrome String?
A palindrome string is a string that reads the same forward and backward. In other words, when the string is reversed, it remains unchanged.
Examples : radar, madam, level, racecar
import java.util.stream.IntStream;
public class PalindromeTest {
public static void main(String[] args) {
String str = "radar";
boolean isPalindrome = IntStream.range(0, str.length() / 2)
.allMatch(i -> str.charAt(i) == str.charAt(str.length() - 1 - i));
if (isPalindrome) {
System.out.println(str + " is a Palindrome String");
} else {
System.out.println(str + " is not a Palindrome String");
}
}
}
Output :
radar is a Palindrome String
FAQ
What is a palindrome string?
A palindrome string is a string that reads the same forward and backward, such as “radar” and “madam”.
How do you find palindrome strings in Java 8?
You can use Java 8 Stream API along with the filter() method and StringBuilder.reverse() to identify palindrome strings.
Which Stream API method is used to filter palindrome strings?
The filter() method is used to filter only palindrome strings from a collection.
Why use StringBuilder reverse() for palindrome checking?
StringBuilder.reverse() provides a simple and efficient way to reverse a string for comparison.
What is the output of the given program?
The output is:[radar, madam]