Was it helpful?

Question

Difference between Function and Predicate in Java 8

JavaObject Oriented ProgrammingProgramming

Function and Predicate both functional interface was introduced in Java 8 to implement functional programming in Java.

Function interface is used to do the transformation.It can accepts one argument and produces a result. On the other side, Predicate can also accept only one argument but it can only return boolean value. It is used to test the condition.

Sr. No.KeyFunctionPredicate
1
Basic
It can take 2 type parameters First one represents input type argument type and second one represents return type.
It can take one type parameter which represents input type or argument type.
2
Return Type
It can return any type of value.
It can only return boolean value
3
Method
It has abstract method apply().
It has abstract method test().
4.
Use Case
It can be used to implement conditional checks
It can be used for the transformation and to the return values.

Example of Predicate

public class Main {
   public static void main(String args[]) {
      List<Integer> numList = new ArrayList<>();
      numList.add(5);
      numList.add(10);
      Predicate<Integer> pred = i -> i > 5;
      numList.stream().filter(pred).forEach(i -> System.out.println(i));
   }
}

Example of Function

public class Main {
   public static void main(String args[]) {
      List<Integer> numList = new ArrayList<>();
      numList.add(78);
      numList.add(10);
      Function<Integer, Integer> fun = i -> i / 2;
      numList.stream().map(fun).forEach(System.out::println);    
   }
}
raja
Published on 09-Sep-2020 14:48:01
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top