Predicate The Functional interface in java


What is a functional interface?  A Functional Interface is an Interface which allows only one abstract method within the interface scope. To use a normal interface there are two steps.
1. Declare one interface with abstract method.

2. Provide  body of Interface  by implementing on a class.

Same happen in case of functional interface. Important difference in functional interface there is only one abstract method declaration. While implementing we use the benefit of single abstract method , we write anonymous function for single abstract method. This functional interface helps us to write lambda in java.


public interface MyFunctionalnterface<T> {
    String funPart(T t);
}public class UseFunctional {
	public static void main(String [] arg) {
		String str =" Functional World !";
		MyFunctionalnterface<String> callFun;
	     
		callFun= (xyz)-> {
			return str + xyz;
		};
		
		System.out.println(callFun.funPart(" in java "));
	    }
}

Some predefined functional interfaces in Java 8.  Programmer frequently use Predicate, Consumer, Supplier. 

  1. public interface Predicate<T>
  2. public interface UnaryOperator<T> extends Function<T,T>
  3. public interface Function<T,R>
  4. public interface Supplier<T>
  5. public interface Consumer<T>
  6. public interface BinaryOperator<T> extends BiFunction<T,T,T>
  7. public interface  BiFunction<T,U,R>

In Java 8, Predicate is a functional interface, which accepts an argument and returns a boolean value. It is used to apply in a filter for a collection of of objects.  abstract method is test(T,t) and return type is boolean. Predicate is defined in java.util.function package

@FunctionalInterface
public interface Predicate<T> {
  boolean test(T t);
}

Predicate has test method having generic parameter template and return boolean value.  this return type is used for testing the condition on collection of object.  Main logic is to test condition and return true or  false. In the Stream we call the method filter and provide a function implementation. this function implementation is body of test method and it execute inline.


List<Integer> result = lstValue.stream()
              .filter(x -> x % 2 == 0 )    //Predicate's test method implementation
              .collect(Collectors.toList());

This program filter the list all even elements. filter (x-> x%2 ==0) generate a new stream. The Collect
method convert intermediate stream into list.

package com.java.example;

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class PredicateExamplee { public static void main(String[] args) { List<Integer> lstValue = Arrays.asList(2,4,6,8,9,10,12,14,15,16,19); List<Integer> result = lstValue.stream() .filter(x -> x % 2 == 0 ) .collect(Collectors.toList()); System.out.println(result); // result = [2, 4, 6, 8, 10, 12, 14, 16] } }
The above scenario we have using the lambda function.  But we are passing the function body directly as an argument in filter method . This body is an implementation of test  method. We can create a method body give it a name and place it into filter method as an argument .

Predicate<Integer> testFunction =  x -> x % 2 == 0
Provide the function name in test implementation. We ill get the same result . Here the testFunction is doing the same job like the above one. we can passing a reference in place of expression.

package com.java.example;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class FunctionAssignPredicate {

  public static void main(String[] args) {
     Predicate<Integer> testFunction =  x -> x % 2 == 0;
     List<Integer> lstValues = Arrays.asList(2,4,6,8,9,10,12,14,15,16,19);
     List<Integer> result = lstValues.stream()
                .filter(testFunction)
                .collect(Collectors.toList());
        System.out.println(result);  
        // result  =  [2, 4, 6, 8, 10, 12, 14, 16]
    }
}
Logical conditions AND ,OR,NOT are easy to use inside test method implementation. let's use AND ,OR,NOT condition inside test  implementation with filter's test method .  We can write two lambda function and pass those lambda function inside the filter method
package com.java.example;import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MultipleFilterPredicate {

    public static void main(String[] args) {

       List<Integer> list = Arrays.asList(3,5,6,7,8,9,15,20);        Predicate<Integer> greaterThan = x -> x > 1;
        Predicate<Integer> lessThan    = x -> x < 10;     // here && condition operator between greater and less values
         List<Integer> collect = list.stream()
                                    .filter(greaterThan.and (lessThan))
                                    .collect(Collectors.toList());        System.out.println(collect);        } // end of main    }  // end of class
we can implement the OR operator in a similar fashion inside the filter method of stream.  
default Predicate<T>  negate() { 
				return (t) -> !test(t);
				} 
The logical negation operator ( ! ) reverses the meaning of its operand. here we can reverse
the condition with negate method of predicate.
package com.java.example;import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class NegatePredicateEample{

public static void main(String[] args) {

       Predicate<String> nameList = x -> x.startsWith("K");
        
        List<String> list = Arrays.asList("Kailash", 
					 "Harish", 
					 "Jagmohan", 
					 "Avtar", 
				         "Sandeep", "Saurabh");
        List<String> collect = list.stream()
                .filter(nameList.negate())
                .collect(Collectors.toList());

        System.out.println(collect);
        //Result : [Harish, Jagmohan, Avtar, Sandeep, Saurabh]
    }   }  // end of class

Done ......

Comments

Popular posts from this blog

NodeJS vs Java

JPA mappedBy and JoinColumn