Sunday, September 7, 2014

Java8 : How to check if number is Palindrome using parallelStream

   The palindrome is case of number is the number thats holds same value forward and backward. One example is the number 22 which holds its value no matter where you start. It's also nice example to train programming and thinking skills. The function can be used nicely for multi-treading computing.  
   Let's create the main class:
...
public static void main(String... arg){
   ...
   SequenceChecker sequenceChecker = new SequenceChecker();
   List<Integer> numbers = Arrays.asList(12, 121, 211, 22);

    numbers.parallelStream().forEach(number ->
         logger.debug("Number = " + number + " isPalindrome= " + sequenceChecker.isPalindrome(number))
    );
   ...
the code is in Java 8 small and readable. We do use to SequenceChecker class to check if the number is palindrome or not. 
  To process isPalindrome check we employ parallelism,  we divide the list of number to the smaller sub-problems and evaluate them. In this case we use newly added API into Java 8 Stream and we use parallelStream() method on the collection which separates the collection into the parallel tasks. 

  The core of the example is the method provided by the SequenceSchecker isPalindrome which task the number form the provided collection. 
...
public boolean isPalindrome(int number){
  return number == reverseNumber(number);
}
...
  The logic of the isPalindrome method is encapsulated inside the private method reverseNumber. This method uses only basic mathematic operations to reverse the provided number.
private int reverseNumber(int number){
   int result = 0;
   while(number != 0){
      result = result * 10 + number % 10;
      number = number / 10;
   }
   return result;
}
  As we process the collection by using the parralelStream implementation so on the output the numbers ordered by resources availability for the task computation. 
Number = 22 isPalindrome= true
Number = 211 isPalindrome= false
Number = 12 isPalindrome= false
Number = 121 isPalindrome= true

No comments: