How to check Palindrome in java using Stream API ?

How to check Palindrome in java using Stream API ?

How to check Palindrome in java using Stream API

In this Java code snippet, a list of strings named `words` is created, containing “radar,” “hello,” and “deified.” Using Java 8 streams, a new list called `palindromes` is generated by filtering the `words` list.

The `filter` operation checks if a string is a palindrome by comparing it to its reverse version. This is achieved by creating a `StringBuilder` and reversing it using the `reverse()` method.

If the reversed string matches the original, it’s considered a palindrome. The `collect` operation assembles the palindrome strings into the `palindromes` list, resulting in a collection of words that read the same forwards and backwards.

 


List<String> words = Arrays.asList("radar", "hello", "deified");
List<String> palindromes = words.stream()
.filter(s -> s.equals(new StringBuilder(s).reverse().toString()))
.collect(Collectors.toList());