Java Lambda Expressions

  • + 6 comments

    Its a bit long but easy to understand...

    public static PerformOperation isOdd()
    {
        return num ->
        {
              if(num%2==0)
                return false;
             else
                return true;
        } ;
    }
    
    public static PerformOperation isPrime()
    {
        return num ->
        {
            int flag = 0;
            for(int i=2;i<=num/2;i++)
          {
               if(num%i==0)
                {
                  flag = 1;
                  break; 
                }
               else
                {
                  flag = 0;
                  break; 
                }
                
          }
          if(flag == 0)
              return true;
          else 
              return false;
        }; 
    }
    
    public static PerformOperation isPalindrome()
    {
        return num ->
        {
          int r,sum=0,temp; 
          temp = num;
           while(num>0)
            {
                r = num % 10;
                sum = (sum*10)+r;  
                num = num/10;  
            }
          if(temp == sum)
            return true;
          else
            return false;
        };
       
    }
    }
    
    • + 0 comments

      For completeness, I implemented a Sieve of Erathosthenes for the prime check. I also treated all negative numbers as not prime, although that can apparently be argued...

    • + 1 comment

      you code is nice and simple and easy for beginners to understand those who are about to learn lambdas....thanks!! next step if you can migrate this code into something called as stream pipelining

      • + 0 comments

        People try too hard to write complex one line solutions to seem smart, but actual clean code looks more like this, it is easy to read and understand.

    • + 0 comments

      I never understood how lambda expressions worked until now, thanks a lot.

    • + 0 comments

      13 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 2 10 2 11 2 12 2 13 PRIME PRIME PRIME COMPOSITE PRIME COMPOSITE PRIME COMPOSITE PRIME COMPOSITE PRIME COMPOSITE PRIME

      Not sure if the isPrime() method works. The loop seems to exit during the first iteration.

    • + 0 comments

      ur isprime() methode seems to be wrong..!! there is no need of else block..

    • + 0 comments

      why no comments?