These expression add functional edge to the language. Let's try to understand that with an example

Before that let me make an statement -

An interface having only one method is called functional interface.

You might have written anonymous class using Runnable ,ActionListener interface . For example :

Public class Engine {

public static void main(String args[]){

new Thread(new Runnable(){

public void run()

{

int count=10

while (count>0){

System.out.println(count);

COUNT--;

}

}).start();

}

in above code we are using Runnable interface an anonymous class.

How to replace anonymous class code with lambda expression ?

Public class Engine {

public static void main(String args[]){

new Thread(()->{

{

int count=10

while (count>0){

System.out.println(count);

COUNT--;

}

}).start();

}

What is different here. new Runnable , public void run is not there is this code. But this works fine

This is done because compiler understand that Thread class implement Runnable interface and there is only one method run() in that class.

So to execute only method of interface We can straight away write the code without interface name and method name. So it seems like anonymous method. That's how we can use lambda expression to replace all anonymous class.

Let's take another example

public class Customer{

isCustomerValid(

roster,

new ValidateCustomer() {

public boolean test(Customer cust) {

return cust.getCountry() == Customer.COUNTRY.US

&& cust.getPoint >= 10

}

}

);

}

In isCustomerValid method ValidateCustomer is anonymous class.

Now consider ValidateCustomer interface is like :

interface ValidateCustomer{

test(Customer cust);

}

This is functional interface. So we can use lambda expression for this just like below code

public class Customer{

isCustomerValid(

roster,

(Customer cust) ->

cust.getCountry() == Customer.COUNTRY.US

&& cust.getPoint >= 10

);

}

So lambda expression is a good way to use functional anonymous method as an argument .

Subscribe via email

About Me

Mobile NO : 7503454801
Email address : manojbharal2@gmail.com
About Blog
Blog consist of posts on java j2ee technical topics. It covers all range of post starting with basic java questions up to advanced j2ee architecture. I am owning this blog. Content being published here is authentic and original . This is growing blog and visitors can expect huge relevant and useful information to enhance their knowledge on subject.
About me
I have total of around 8 years of experience in java j2ee technologies and am working on multiple business domain technical projects in all range of industries .