To find all Palindrome String in given Array of string in Java 8, we are using the Stream api function.
- Create an Array of string data.
- Add this array to a list.
- Now this list to stream using arrayList.stream() method.
- The StringBuilder’s reverse() method is used to reverse the string.
- Inside filter, original string is compared to reversed string to find the if it is a palindrome.
- From collect() method, we collect all the palindrome string.
- Print all the palindrome string.
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<String> list = Arrays.asList(arr);
List<String> palindromeString = list.stream().filter(r -> r.equals(new StringBuilder(r).reverse().toString()))
.collect(Collectors.toList());
System.out.println("Print all the palindromes string are :- " + palindromeString);
}
}
Output :-
Print all the palindromes string are :- [radar, madam]