Flat Preloader Icon

Java Lambda Expressions

Lambda expressions were introduced in Java 8 to bring functional programming constructs to the Java language. They provide a concise way to represent anonymous functions, enabling you to write more efficient and expressive code.

Some Key Points To Understand About Java Lambda Expressions

Functional Interfaces:

  • Lambda expressions work with functional interfaces, which are interfaces that have only one abstract method. These interfaces serve as the target types for lambda expressions.

Syntax:

  • Lambda expressions are written in the form (parameters) -> expression. If the lambda body requires multiple lines, it is enclosed in curly braces.

Type Inference:

  • The Java compiler can often infer the type of the lambda parameters, making it possible to write more concise code.

Variable Capture:

  • Lambda expressions can access variables from their enclosing scope. However, these variables must be effectively final, meaning they should not be modified after the lambda expression is defined

Use Cases:

  • Lambda expressions are commonly used with the Streams API to perform operations on collections. They can also be used in functional interfaces like Runnable, Consumer, Supplier, and more.
Here’s an example of how you can use lambda expressions with the List and forEach method:
				
					List<String> names = Arrays.asList
("John", "Doe", "Jane", "Doe");

// Using lambda expression with forEach method
names.forEach(name -> System.out.println
("Hello, " + name));

				
			
  • In this example, the lambda expression name -> System.out.println(“Hello, ” + name) is passed as an argument to the forEach method, which applies this function to each element in the list.
Lambda expressions have significantly improved the way Java handles functional programming paradigms, making code more concise and readable. They are widely used in modern Java development, especially when working with collections and stream processing.

Java Lambda Expression Example With Or Without Return Keyword

  • In Java lambda expression, if there is only one statement, you may or may not use return keyword. You must use return keyword when lambda expression contains multiple statements.
				
					interface Addable{  
    int add(int a,int b);  
}  
  
public class LambdaExpressionExample6 {  
    public static void main(String[] args) {  
          
        // Lambda expression without return keyword.  
        Addable ad1=(a,b)->(a+b);  
        System.out.println(ad1.add(10,20));  
          
        // Lambda expression with return keyword.    
        Addable ad2=(int a,int b)->{  
                            return (a+b);   
                            };  
        System.out.println(ad2.add(100,200));  
    }  
}  
				
			

Output:

				
					30
300