Learn in Java
 


   

Java 8 - Lambda Expressions

 
To understand Lambda Expressions, we first need to understand what a Functional Interface is. Lambda Expressions treats functionality as method arguments or code as data. Very difficult definition to understand ? Me too!! Simply said, lambda expressions simplifies the syntax when we have only one method in an interface which needs to be called. No more weird anonymous inner class syntax.

Remember:
The lambda expressions can be specified in 3 different styles:
      
1. ([DataType] parameter(s)) -> statement

    For example, e -> System.out.println("Using flatMap() : " + e.size);

2. ([DataType] parameter(s)) -> { statements }

    For example, b -> {
                System.out.println("Thread Name in map : " + Thread.currentThread().getName());
                return b.toUpperCase();
              }

3. ([DataType] parameter(s)) -> expression

    For example, (b1, b2) -> b1 + b2;

For more examples, see Stream examples.

The DataType is an optional field and can be ommitted.

For instance, consider the below example,

package com.learninjava;


/**
 * @author learninjava.com
 * @see www.learninjava.com
 */
public class LambdaExpressionsExample1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		// Using the Anonymous inner class syntax
		hitThePigUsingAngryBird(new AngryBird() {
			
			public void hitThePig() {
				System.out.println("Sucessfully sent an Anonymous bird to hit the pig...");
			}
		});

		// Using the new java 8 Lambda Expressions syntax
		hitThePigUsingAngryBird(() -> System.out.println("Sucessfully sent a Lambda Expression bird to hit the pig..."));
	}
	
	private static void hitThePigUsingAngryBird(AngryBird ab) {
		ab.hitThePig();
	}

	@FunctionalInterface
	public interface AngryBird {
		
		public void hitThePig();
	}
}

Output:
Sucessfully sent an Anonymous bird to hit the pig...
Sucessfully sent a Lambda Expression bird to hit the pig...


 

This example defines a functional interface and tries to access the method in it using both anonymous inner class syntax and usign Java 8 lambda expressions syntax.

Using the anonymous inner class syntax is understandable but we are creating a new class with the complete method declaration and the logic inside the method. However, in case of lambda expressions, we are doing the same using a single statement. So, why should we need to provide the entire class and method definitions when our task is to add logic only to the method in the class. Lambda expresssions does exactly this.

In the above example, we refer to the method hitThePig() by just (). The logic inside the method is provided on the right had side of -> operator. This is like saying to the compiler "call the only method in the functional interface whose implementation is provided after -> operator".

If the method accepts a parameter, say the color of the bird then the syntax slightly varies.

The same is shown with an example below:

package com.learninjava;


/**
 * @author learninjava.com
 * @see www.learninjava.com
 */
public class LambdaExpressionsExample2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		// Using the Anonymous inner class syntax
		hitThePigUsingAngryBird(new AngryBird() {
			
			public void hitThePig(String birdColor) {
				System.out.println("Sucessfully sent an Anonymous bird with birdColor " + birdColor + " to hit the pig...");
			}
		});

		// Using the new java 8 Lambda Expressions syntax
		hitThePigUsingAngryBird((String birdColor) -> System.out.println("Sucessfully sent a Lambda Expression bird with birdColor " + birdColor + " to hit the pig..."));
	}
	
	private static void hitThePigUsingAngryBird(AngryBird ab) {
		String birdColor = "RED";
		ab.hitThePig(birdColor);
	}

	@FunctionalInterface
	public interface AngryBird {
		
		public static final String birdColor = "";
		public void hitThePig(String s);
	}
}

Output:
Sucessfully sent an Anonymous bird with color RED to hit the pig...
Sucessfully sent a Lambda Expression bird with color RED to hit the pig...

Observe now that the method hitThePig(birdColor) now accepts an argument called birdColor. The rest is self-explanatory.

Remember:
The data type of the argument birdColor in the below statement is a not mandatory requirement.
That means instead of writing the following statement,

  hitThePigUsingAngryBird((String birdColor) -> ...

we can simply omit the data type and modify the statement as below:

  hitThePigUsingAngryBird((birdColor) ->

This is perfectly legal and valid syntax.

 
   

Related Articles

Java 8 Stream
Java 8 Functional Interfaces
Equals and HashCode
 
   

Recommended Articles

User and Daemon Threads
Thread States
Restful WebService using CXF
Restful Client using CXF
SOAP WebService using CXF
SOAP Client using CXF




LIKE/SHARE
 
 
 
Download Source:

Comments:


 

Top Picks

1. Top 5 websites offering free e-books

2. Top 10 websites for free Java Articles and Tutorials

3. Top 5 websites for Java Certifications

4. Top 5 Softwares for Java developers




   
   
   
 
 
© Copyright 2017. All rights reserved. All trademarks and logos belongs to their owners.         Website Counter