Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between Function and Predicate in Java 8
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. | Key | Function | Predicate |
|---|---|---|---|
| 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);
}
}Advertisements