Check if a String is a Palindrome using Streams?

Problem:
How do you check whether a string is a palindrome using Java 8 Streams (without reversing it)?
A palindrome is a string that reads the same forwards and backwards — like “madam” or “level”

✅Example 1: Without Reverse

import java.util.stream.IntStream;

public class PalindromeCheckStream {

    public static void main(String[] args) {
        String input = "madam";

        boolean isPalindrome = IntStream.range(0, input.length() / 2)
                .allMatch(i -> input.charAt(i) == input.charAt(input.length() - 1 - i));

        System.out.println("String is Palindrome: " + isPalindrome);
    }
}

✅ Output:

String is Palindrome: true

✅ Explanation:

  • We use IntStream.range(0, input.length() / 2) to generate a stream of indices from 0 to input.length() / 2 - 1.
  • For each index i, we check: input.charAt(i) == input.charAt(input.length() - 1 - i) This compares the character from the start of the string with the corresponding character from the end.
  • .allMatch() returns true if all comparisons pass (i.e., the string is a palindrome).
  • We only check up to half the string because beyond that would be redundant.

✅ Alternative Approach – Using StringBuilder (without using explicit loops):

import java.util.stream.IntStream;

public class PalindromeCheckStream {

    public static void main(String[] args) {
        String input = "Java knowledge Base";

        // Normalize the string: remove spaces and convert to lower case for accurate comparison
        String normalizedInput = input.replaceAll("\\s+", "").toLowerCase();

        boolean isPalindrome = normalizedInput.equals(
                new StringBuilder(normalizedInput).reverse().toString()
        );

        System.out.println("Input Parameter: " + input);
        System.out.println("String is Palindrome: " + isPalindrome);
    }
}

✅Output:

Input Parameter: Java knowledge Base
String is Palindrome: false

✅ Explanation:

  • First, we normalize the string by:
    • Removing spaces (replaceAll("\\s+", ""))
    • Converting to lowercase (toLowerCase())
      This ensures a fair comparison (ignoring case and spaces).
  • Then, we use StringBuilder’s .reverse() method and check: normalizedInput.equals(new StringBuilder(normalizedInput).reverse().toString());
  • This returns true if the normalized string is the same when reversed, and false otherwise.

Java developer with 9+ years of IT experience, sharing tutorials and tips to help learners master Java programming.

Leave a Reply

Your email address will not be published. Required fields are marked *