Palindrome with Java 8 and Java Posix Classes

There are different way to write a method to check if a Sentence is a palindrome. One interesting way it’s using Java 8 and the Posix character classes( at least for US-ASCII)

Assume that we have a sentence like “Was it a car or a cat I saw?”. We can replace all symbols that are not to be considered and lower case everything. Then using IntStream in the range of half of the size of the sentence go and check if first and last character match.

   public boolean isPalindrome(String text) {
    String temp  = text.replaceAll("\\P{Alnum}", "").toLowerCase();
    return IntStream.range(0, temp.length() / 2)
      .allMatch(i -> temp.charAt(i) == temp.charAt(temp.length() - i - 1));
    }

Leave a Reply

Your email address will not be published.

*