Saturday 26 October 2019

Function Interface

  1. Function interface is a part of the java.util.function package which has been introduced in java 8.
  2. Functions are exactly same as predicates except that functions can return any type of result but function should (can) return only one value and that value can be any type as per our requirement. 
  3. Function interface present in Java.util.function package. 
  4. Functional interface contains only one method i.e., apply().
   Syntex:
                     interface function(T,R) {   
                                  public R apply(T t); 
                        }
                  T: 
denotes the type of the input argument.
                  R: denotes the return type of the function.

  Example 1:Write a function to find length of given input string
Output:

6

11

25

100

 Note: Function is a functional interface and hence it can refer lambda expression.

Differences between predicate and function 
     Predicate:
  1. To implement conditional checks We should go for predicate .
  2.  Predicate can take one type Parameter which represents Input argument type. Predicate<T> 
  3. Predicate interface defines only one method called test().
  4. public boolean test(T t).
  5. Predicate can return only boolean value. 
  Function:
  1. To perform certain operation And to return some result we Should go for function.
  2. Function can take 2 type Parameters. First one represent Input argument type and Second one represent return Type.  Function<T,R>
  3. Function interface defines only one Method called apply(). 
  4. public  R  apply(T t) .
  5. Function can return any type of value.
Note: Predicate is a boolean valued function and(), or(), negate() are default methods present inside Predicate interface. 

Example 2.1:  To remove spaces present in the given String by using Function .
                2.2:   How to find Number of spaces present in the given String by using Function.


Output:-
HelloSudhirhowareyou
4

Example 3: To find Student Grade by using Function

Share this

2 Responses to "Function Interface"

  1. Very good understandings about the Functional Interface. Can you give me little more examples.

    ReplyDelete
    Replies
    1. Thank you, will give you more details and examples soon. :)

      Delete