Saturday, March 3, 2018

Predicates

A predicate is a function with a single argument and returns boolean value.
To implement predicate functions in java, oracle people introduced predicate interface in 1.8 version (i.e., Predicate).
Predicate interface present in java.util.function package.
It’s a functional interface and it contain only one method i.e., test().

Ex:
interface Predicate<T> {
    public Boolean test(T t);
}

As predicate is a functional interface and hence it can refers lambda expression.

Ex:1

Write a predicate to check whether the given integer is greater than 10 or not.

Ex:

public boolean test(Integer I) {
    if(I>10) {
            return true;
    }
     else {
              return false;
    }
}

(Integer I) > {
      If(I>10)
         return true;
     else
         return false;
}
I > (I>10);

Predicatep=I –> (I>10);
System.out.println(p.test(100)); true
System.out.println(p.test(7)); false

Program

import java.util.function;
class Test {
           public static void main(String[] args) {                 
                predicate<Integer> p = I > (i>10);
                System.out.println(p.test(100));
                System.out.println(p.test(7));
                System.out.println(p.test(true)); //CE
           }
} 

# 1 Write a predicate to check the length of given string is greater than 3 or not.

Predicatep = s –> (s.length() > 3);
System.out.println (p.test(“rvkb”)); true
System.out.println (p.test(“rk”)); false

# 2 Write a predicate to check whether the given collection is empty or not.

Predicate p = c –> c.isEmpty();  

Predicate joining

It’s possible to join predicates into a single predicate by using the following methods.

and()
       or()
       negate() 
These are exactly same as logical AND, OR complement operators.

Ex:

import java.util.function.*;
class test {
      public static void main(String[] args) {
         int[] x = {0, 5, 10,15, 20, 25, 30};
         predicate<integer> p1 = i->i>10;
         predicate<integer> p2 = I -> i%2==0;
         System.out.println(The Number Greater Than 10:);
         m1(p1, x);
         System.out.println(The Even Numbers Are:);
         m1(p2, x);
         System.out.println(The Numbers Not Greater Than 10:);
         m1(p1.negate(), x);
         System.out.println(The Numbers Greater Than 10 And Even Are:);
         m1(p1.and(p2), x);
         System.out.println(The Numbers Greater Than 10 OR Even:);
         m1(p1.or(p2), x);
      }
       public static void m1(predicate<integer>p, int[] x) {
            for(int x1:x) {
                if(p.test(x1))
                   System.out.println(x1);
            }
      }
} 

No comments: