Connect with us

CORE JAVA

Predefined Functional Interface in Java 8

Predefined_Function

Inroduction

In any programming languages, efficiency and readability are considered a  crucial aspect. Java 8 introduced many features to make code more concise, readable, and efficient. Predefined functional  interface is one of them, which serves as a versatile tool that can significantly improve our development process by reducing line of code. Most common predefined functional interfaces provided by Java API are Predicate, Function, Consumer, Supplier. 

Interface Predicate<T>

Predicate is a functional interface which represents  a boolean-valued function of one argument and present in java.util.function package. It is used to test objects whether they satisfy certain conditions or not (true or false).

Predicates are extremely  flexible and handy which  can be applied in a number of scenarios like filtering collections to defining complex conditions for data processing. It is compatible with Java 8. By using Predicates with streams, we can perform very complex operations  on collections with minimal effort.

Predicate is useful in so many ways like filtering elements, to find matching items, or perform any other form of conditional processing.

Methods present in Predicate

As we know, in any Functional Interface, only one abstract method is present along with any number of default & static method. The single Abstract Method (SAM) present in Predicate is test(Object). Lets see few code example below.

 

1: boolean test(Object)

 Functional method of Predicate interface is test(Object) and defined as:

  interface  Predicate<T>{

     boolean test(T t);   

}

Example 1: Check number >10

Lets use Predicate to test if given number is greater than 10 or not & return equivalent boolean value.

				
					import java.util.function.Predicate;

public class MainPredicate {

    public static void main(String[] args) {

        Predicate<Integer> p=(val)->{

            if (val>10){
                return true;
            }else{
                return false;
            }
        };
        System.out.println(p.test(20)); // true
        System.out.println(p.test(5));  // false
    }
}
				
			

Every functional interface refer to lambda expression , we can more siplify above function by converting it in the  equivalent lambda expression.

				
					Predicate<Integer> p=I->I>10;

 System.out.println(p.test(20)); // return true;
 System.out.println(p.test(5));  // return false
				
			

Example 2: Check length of the string >5

				
					public class MainPredicate {

    public static void main(String[] args) {

       Predicate<String> checkLength=str->str.length()>5;
        System.out.println(checkLength.test("Springboot")); // true
        System.out.println(checkLength.test("Java"));  // false
    }
}
				
			

Example 3: To check given Collection object is empty or not.

				
					import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class MainPredicate {

    public static void main(String[] args) {

        List<String> al=new ArrayList<>();
        al.add("Java");
        al.add("Spring");
       Predicate<List> checkEmpty=myList->myList.isEmpty();
       System.out.println(checkEmpty.test(al)); // false
        
        List<String> noElementList=new ArrayList<>();

        Predicate<List> check=myList->myList.isEmpty();
        System.out.println(check.test(noElementList)); // true
    }
}
				
			

Predicate other default & static methods

There are other static & default  methods present in Predicate<T> functional interface along with single abstract method test(Object).

 

default Predicate<T>    and(Predicate<? super T> other)

Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.

In Java 8 Functional Interface, we can combine multiple predicates into a single one using logical operators. This allows for more complex conditional checks by joining different predicates togethe.

Lets take an example where we have two Predicates and then joining them using logical AND

Example 1: joining two Predicates

				
					import java.util.function.Predicate;
public class MainPredicate {

    public static void main(String[] args) {

        //Predicate 1st
       Predicate<String> lengthGreaterThanFive=s1->s1.length()>5;

      // Predicate 2nd
       Predicate<String> lengthLessThan10=s2->s2.length()<10;

       // Join predicates using logical AND
       Predicate<String> check=lengthGreaterThanFive.and(lengthLessThan10);

        System.out.println(check.test("Java"));  // false
        System.out.println(check.test("javaDSA")); // true
    }
}

				
			

Example 2: joining two Predicates

Here, there are two predicates to check number is even and greater than 10. We have an array of Intergers value & check every value to evaluate either true or false.

				
					import java.util.function.Predicate;
public class MainPredicate {

    private static Predicate<String> lengthGreaterThanFive;

    public static void main(String[] args) {

        int[] numArr={5,7,15,18,27,30,35};
        Predicate<Integer> p1=I->I>10;
        Predicate<Integer> p2=I->I%2==0;

        Predicate<Integer> check=p1.and(p2);
        checkEvenAndGreaterThanTen(numArr,check);
    }

    private static void checkEvenAndGreaterThanTen(int[] numArr, Predicate<Integer> check) {

        for (Integer val:numArr){

            if (check.test(val)){
                System.out.println( "Condition true "+ val+ " Number is even  & greater than 10");
            }else{
                System.out.println( "Condition false "+ val+" Number is either odd or less than 10");
            }
        }
    }
}

				
			
				
					Output:

Condition false 5 Number is either odd or less than 10
Condition false 7 Number is either odd or less than 10
Condition false 15 Number is either odd or less than 10
Condition true 18 Number is even  & greater than 10
Condition false 27 Number is either odd or less than 10
Condition true 30 Number is even  & greater than 10
Condition false 35 Number is either odd or less than 10
				
			

default Predicate<T> negate()

The pre­dicate interface offe­rs a negate() method that re­turns a new predicate and this ne­w predicate repre­sents the logical opposite of the­ original one.

				
					import java.util.function.Predicate;
public class MainPredicate {

    private static Predicate<String> lengthGreaterThanFive;

    public static void main(String[] args) {

        // Predicate to check if number is even
        Predicate<Integer> even=I->I%2==0;
        // Creating new predicate by negating above one
        Predicate<Integer> negate_even=even.negate();

        // print the predicate output
        System.out.println(even.test(10));   // true
        System.out.println(negate_even.test(10));  // false
    }
}
				
			

static  Predicate isEqual(Object obj)

Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).

This method is helpful for making tests to see if one object is equal to a specific object. It can be especially useful when used with other functional tools like the filter() method in data streams or when putting together complex tests in stream api

 Read more..  

 

 

				
					import java.util.function.Predicate;

public class EqualPredicate {
    public static void main(String[] args) {

        Predicate<String> isEqualName = Predicate.isEqual("david");

        System.out.println(isEqualName.test("david")); // true
        System.out.println(isEqualName.test("alex")); //  false
    }
}
				
			
				
					Output:
true
false
				
			

More in CORE JAVA