Use case of predefined functional interface called Function in java8

                                     Java8 Function<T,R>


 Function<T,R>: Function is a  functional interface .Its having only one abstract method called apply();

 like the below

Function<T,R>


Here apply method takes T is  input and return  R is output.

Lamda Expression: Lambda expressions are nothing but the implementation of the functional interface.

We can provide logic to apply method using lambda expression to convert  from T to R like the below

                     (T t)-> return R .

Use Case: If we are invoking a StudentController from Postman or any Service and passing Student information as json then Controller will receive Student object then we need convert into entity(EStudent)  to persist information into DB.

Here Student is model class which is having variable names similar to json input.

EStudent is an entity class having the object relational  mapping with STUDENT table.

So In Service class we need to convert model(Student) to entity(EStudent)with the help of utility class called   mapper(StudentMapper).There we have a utility method called entityMapper(). 

Model class:

----------------

Model



Entity

-------

Entity


 Now I want to convert model instance to entity with the help of entityMapper method  like the below

Mapper



Mapper class utilized by the service class for converting from model to entity (business logic)

Here If we observe carefully then we got to know that STUDENT table is expecting Student name is combination of firstName and seconedName.


Service class utilize the mapper class and then it will save the entity using StudentRepo like the below.

Service class
StudentMapper will take Student(model) as input and returns the EStudent(entity) as response.

2.Why do we need Function<T,R> instead of normal convert method in utility class.

Ans:  The Java compiler evaluates lambda expressions and method references in the argument list at the called location.Lambda expressions evaluated when its required for our case when we call apply method then only lamda expression(conversion logic) evaluated.


Happy Learning  :)

Feel free to comment If you  observe any.

Comments

Popular posts from this blog

Proxy Design Pattern Using Spring AOP

Strategy Design Pattern

Use cases of Supplier in java 8