1

I'm trying to take a list of strings from a user, store them in an array, and one-by-one, pass them through a function (oddPalindrome(results[i])) that returns a boolean indicating whether or not the string is a palindrome. Then it simply prints out whether that's a palindrome or not to the user. Below is the for loop I have constructed for it. I'm trying to figure out how to do this with a java stream, instead of a for-loop. Any help?

for (int i = 0; i < results.length; i++) {
  System.out.print(results[i] + " ");
  if (StringOperations.oddPalindrome(results[i])) {
    System.out.println("is a palindrome");
  } else {
    System.out.println("is NOT a palindrome");
  }
}
  • It would be helpful to us if you could show the code for the oddPalindrome() method – LuckyBandit74 Jun 22 '21 at 20:09
  • you could do the prints in your oddPalindrome module and after that simply call it from the forEach, something like `results.forEach(StringOperations::oddPalindrome)`. Also, Is there any specific reason to use stream? Read the stackoverflow question on when you should prefer what https://stackoverflow.com/questions/44180101/in-java-what-are-the-advantages-of-streams-over-loops – Manish Karki Jun 22 '21 at 20:15

2 Answers2

3

Try this.

Stream.of(results)
    .forEach(s -> System.out.printf("%s is %sa palindrome%n",
        s, StringOperations.oddPalindrome(s) ? "" : "NOT "));
1

You can make use of the forEach method of stream api. This method takes a consumer interface

str.stream().forEach(string ->{ 
        System.out.println(StringOperations.oddPalindrome(new StringBuilder(string)) ? string + " is Palindrome": string +" is NOT a palindrome");                  
    });
Hrishikesh
  • 21
  • 3