Lambda

Benefits of Lambda
1. To enable functional programming in java.
2. Write more readable, maintainable and concisely.
3. Write one API very easily and effectively.
4. To enable parallel processing.

What is Functional programming?

  • A declarative way of programming in which function definitions are trees of expressions that map values to other values
  • Rather than a sequence of imperative statements which update the running state of the program.
  • Reference

Explaining Lambda :
Since java is a object oriented language and if we create a function/method in java we need to create a class for it but suppose if the class is has only one method and we don’t want to create a class just to store one method in it then in that case we can use lambda
So what is lambda? Just like we assign a value to a variable like String name = “Java” or int x = 10 , we can assign a function itself to a variable.
Lets us take an example of

Interface obj = public void perform(){
                    System.out.println("Hello World");
              }

So what all things can be removed from the above method perform to make it more concise? Since the function will be available to all the method which has the variable hence it make no sense to add access modifiers lets remove that.

//Removed access specifiers
Interface obj = void perform(){
                    System.out.println("Hello World");
              }

Now in the above code what can be removed to make it more concise? since the name of the function is required to call it but if it assigned to a variable we don’t require name of the function hence remove it and check how it looks

//Removed name of the function
Interface obj = void (){
                    System.out.println("Hello World");
              }

Now when you look at the above code it is half way reached to the lambda expression, now what java 8 compiler says is the block of code which is assigned to temp variable and java 8 compiler can identify the return type of the block of code just by looking at the block of code we dont want explicitly notifying the return type of variable in case of lambda hence we can remove that too, now the function that is assigned to a variable looks something like below

//Removed the return type of the method
Interface obj = (){
                    System.out.println("Hello World");
              }

Good now we have create a block of code which can be assigned to a variable but how can we tell the compiler that this is a lambda express? By using the symbol -> in between the bracket of parenthesis and curly braces of code, now after adding that the code looks some thing like this.

//Added the symbol-> to make java compiler understand that it is a lambda exp
//Lambda Expression 1
Interface obj = () -> {
                    System.out.println("Hello World");
              }

Now if your code has only one line then you can also remove the curly braces and the code looks something like this

//Curly braces can be removed if code is of single line
//Lambda Expression 2
Interface obj = () -> System.out.println("Hello World");

Now when suppose you have a lambda expression when returns a value, following the above steps it would look something like this :

Interface obj = (int a, int b) -> return a + b;
//Not valid keyword return since it is a onliner code

But since your code is just one line you can skip the keyword return as well, after removing that the code will look something like this

//Since since line code we can skip keyword return
//Lambda Expression 3
Interface obj = (int a, int b) -> a + b;

Now when you see the example above you can see that in lambda we are implementing one of the function declared in the interface, hence we have the data type of the parameters declared in the interface itself and hence we do not require the type of inputs to be mentioned in the lambda hence we can remove that as well.

//Since input parameters data type is mentioned in function declaration of interface we can remove that from the below lambda expression
//Lambda Expression 4
Interface obj = (a,b) -> a + b;

Now suppose we have only one input argument mentioned in the lambda then we can remove the brackets from the lambda as well

//one input argument example
Interface obj = (a) -> a *2 ;

Then we can remove the brackets from the above example since we can omit it in lambda the expression looks like this

//one input argument example
//Lambda Expression 5
Interface obj = a -> a *2 ;

How java 8 can be implemented with the traditional java code ?

  • We can replace the anonymous inner class with Lamda
  • No more need to declare an implementation for a Interface

Example 1: Replacing Anonymous inner class with Lamda

File dir = new File("/home/temp");
		
		FileFilter fileFilter = new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(".java");
			}
		};
		
		FileFilter fileFilterLamda = (File pathname) -> pathname.getName().endsWith(".java"); 
		
		System.out.println("Anonymous Inner Class :");
		for(File f : dir.listFiles(fileFilter)) {
			System.out.println(f);
		}
		
		System.out.println("Using Lamda");
		for(File f : dir.listFiles(fileFilterLamda)) {
			System.out.println(f);
		}

Example 2: Replacing Anonymous inner class with Lamda

Runnable runnable = new Runnable() {
			@Override
			public void run() {
				for(int i=0;i<3;i++) {
					System.out.println("Hello World : "+i);
				}
			}
			
		};
		Thread t = new Thread(runnable);
		t.start();
		t.join(); //waiting for execution to complete
		
		//Sampe can be impelmented in Lamda
		
		Runnable runnableLamda = () -> {
			for(int i=0;i<3;i++) {
				System.out.println("Hello World from Lamda : "+i);
			}
		};
		
		Thread tLamda = new Thread(runnableLamda);
		tLamda.start();
		tLamda.join(); //waiting for execution to complete

Leave a Comment