Created
January 3, 2014 01:26
-
-
Save netdance/8230850 to your computer and use it in GitHub Desktop.
Writing a palindrome program with Java 8 Streams and Method Expressions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package testpalindrome; | |
import java.nio.file.*; | |
import java.util.stream.Stream; | |
public class TestPalindrome { | |
// system dependant path of dictionary - this is where it is on Mac | |
private static final String dictpath = "/usr/share/dict/words"; | |
public static void main(String[] args) throws Exception { | |
long starttime = System.currentTimeMillis(); | |
Path dict = Paths.get(dictpath); | |
Stream<String> wordStream = Files.lines(dict); | |
long palindrome = wordStream | |
.filter(TestPalindrome::isPalindrome ) // find all palindromes | |
.peek(System.out::println) // write each match | |
.count(); // terminal - return a count | |
System.out.println("Count of palindromes: "+palindrome); | |
System.out.println("Total time elapsed = "+ | |
(System.currentTimeMillis() - starttime)+" milliseconds"); | |
} | |
private static boolean isPalindrome(String word) { | |
boolean isEven = word.length() % 2 == 0; | |
return isPalindrome(word, isEven, isEven ? 0 : 1); | |
} | |
private static boolean isPalindrome(String word, boolean isEven, int offset) { | |
int midpoint = word.length() / 2; | |
if (offset > midpoint + (isEven ? -1 : 0) ) { | |
return true; | |
} | |
char xchar = word.charAt(midpoint - offset + (isEven ? -1 : 0)); | |
char ychar = word.charAt(midpoint + offset); | |
if (xchar != ychar) { | |
return false; | |
} | |
return isPalindrome(word, isEven, offset + 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment