Lambda Expression in Java: Usage and Examples

Updated on September 17, 2024

Article Outline

Java is an object-oriented programming language used in various applications and Game development. It is a multi-platform, object-oriented, network-centric language that can be used as a platform. It is a fast, secure, reliable programming language for coding everything from mobile apps and enterprise software to big data applications and server-side technologies.

What is Lambda Expression in Java?

Lambda expressions were introduced in Java 8 to allow you to implement one function interface. They are anonymous functions that add functional programming techniques to Java. Writing code in a specific function is easier than using anonymous inner classes.

 

The following program demonstrates the lambda expression:

 

Program

interface Greeting { void sayHello(String name) ; } class Main{ public static void main(String args[]){ Greeting greeting = name -> System.out.println("Hello "+name+"!") ; greeting.sayHello("Neeraj Kumar"); greeting.sayHello("Harry Potter") ; } }

Output

Hello Neeraj Kumar! Hello Harry Potter!
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Java Lambda Expression Syntax

 

1. No Parameter Syntax

 

In this case, we don’t need the required input parameter in the lambda functions.

 

// No Parameter Syntax

 

() -> {body of function}

2. One Parameter Syntax

 

In this case, we need to pass one parameter. However, we don’t need to specify the parameter type because the compiler automatically discovers it in Java.

.

// One Parameter Syntax

( p1 ) -> {body of function}

 

3. Multiple Parameter Syntax

 

In this case, we can pass more than two parameters in the lambda expression. You don’t need to specify the parameter for both parameters.

 

// Two Parameter Syntax

( p1, p2 ) -> {body of function}

Lambda Use Cases in Java

A lambda expression is very useful in various situations. It provides concise implementations of function interfaces, allowing simple behaviors to be repeated without complex implementations. There are five fundamental principles of functional programming in Java:

 

  • First-Class Functions: Functions can be treated like variables, passed as arguments, returned by other functions, and assigned to variables in Java
  • Function Composition: Combining simple functions creates a more complex function interface.
  • Pure Functions: The function operates independently of the external state and avoids side effects, leading to more predictable and reliable source code.
  • High-Order Functions: Function that accepts other functions as the parameter and returns as the function their result.

Java Lambda Expression Examples

Example 1: Without Using Lambda expression

Using the anonymous class, we can also implement the functional interface in Java without using the lambda expression. The following code demonstrates the code without using the anonymous lass:

 

Program

@FunctionalInterface interface MyName{ public void SayMyName(); } public class Main { public static void main(String[] args) { MyName person = new MyName(){ @Override public void SayMyName(){ System.out.println("Harry Potter"); } }; person.SayMyName(); } }

Output

Harry Potter

Example 2: Using the Lambda Expression

 

@FunctionalInterface  //It is optional interface MyName{ public void SayMyName(); }  public class Main { public static void main(String[] args) {  //implementing with lambda  MyName p2 = () -> { System.out.println("Voldemort"); };  // function call. p2.SayMyName(); } }

Output

Voldemort

Example 3: Java Lambda Expression with No Parameter

 

We will use the Java lambda expression to create an interface in this example. However, we don’t use the input parameters.

 

Program

interface speaker { public String say(); } public class Main { public static void main(String[] args) { speaker ob = () -> { return "Voldemort is laughing"; }; System.out.println(ob.say()); } }

Output

Voldemort is laughing

Example 4: Java Lambda Expression with a Single Parameter

In this example, we will pass one parameter in the lambda expression in Java.

 

Program

interface Speaker{ public String say(String name); }   public class Main{ public static void main(String[] args) {   Speaker ob = (name) -> { return "Hello, "+name; };   System.out.println(ob.say("Himanshu")); Speaker ob1 = name ->{ return "Hello, "+name; }; System.out.println(ob1.say("Neeraj")); Speaker ob2 = name ->"Hello, "+name; System.out.println(ob2.say("Voldemort")); } }

Output

Hello, Himanshu Hello, Neeraj Hello, Voldemort

Example 5: Java Lambda Expression with Multiple Parameters

 

In this example, we will pass many input parameters for our lambda expression.

 

Program

interface MyInter{ int add(int a,int b); } public class Main{ public static void main(String[] args) { MyInter ob1 = (a,b) -> (a+b); System.out.println(ob1.add(134,5034)); MyInter ob2 = (int a,int b) -> (a+b); System.out.println(ob2.add(340,3050)); } }

Output

5168 3390

Example 6: Iterating Collection Using the forEach Loop

In this example, we will use a forEach loop to run over the list of names then we will use the lambda expression in Java to grab the element from the list and print it.

 

Program

import java.util.*; public class Main{ public static void main(String[] args) { List<String> list=new ArrayList<String>(); list.add("Computer"); list.add("Rohit"); list.add("Rajkumar"); list.add("Voldemort"); list.add("Matter") ; list.add("Singhaniya")  ; list.add("Katerina") ; list.forEach( (element)->System.out.println(element) ); } }

Output

Computer Rohit Rajkumar Voldemort Matter Singhaniya Katerina

Example 7: Java Lambda Expression with or without Return Keyword 

A Java lambda expression contains only one statement, so we can avoid using the return keyword. However, when we use a lambda expression to compress multiple statements, we must use the return keyword.

interface MyInter{ int add(int a,int b); }   class Main { public static void main(String[] args) { MyInter ob = (a,b) -> (a+b); System.out.println(ob.add(100,20)); MyInter ob2 = (int a,int b) -> { return (a+b); }; System.out.println(ob2.add(100,200)); } }

Output

120 300

Example 8:  Java Lambda Expression – Creating Thread 

We can also use the lambda expression for threading. The following program implements the run method in Java. The code below shows two implementations for creating tread on the Runnable interface.

class Main{ public static void main(String[] args) { Runnable ob1 = new Runnable(){ public void run(){ System.out.println("It is the first thread"); } };   Thread thread1=new Thread(ob1); thread1.start();   Runnable ob2 = () -> { System.out.println("It is the second thread"); };   Thread thread2 = new Thread(ob2); thread2.start(); } }

Output

It is the first thread It is the second thread

Lambdas as Objects

The lambda expression in Java is an object. It can be assigned to a variable and passed around like any other object. The following program demonstrates Lambdas as Objects.

 

Program

interface MyComparator { public boolean compare(int a1, int a2); } public class Main { public static void main(String[] args) { MyComparator myComparator = (a1, a2) -> a1 > a2; boolean result = myComparator.compare(2, 5); System.out.println(result); } }

Output

False

Accessible Variable

Under some conditions, A lambda expression can access the variable that is defined outside the lambda function body. Java lambdas can access the following types of variables:

 

  • Local Variables
  • Instance Variables
  • Static Variables

Local Variables

Lambda Expression can access the local variables of the enclosing scope. We need to follow some rules to access the local variables in Lambda depression.

 

  • We cannot declare a local variable with the same name already declared in the enclosing scope of a lambda expression since a lambda expression can’t define a new scope as an anonymous inner class does.

 

  • We cannot assign any value to the lambda expression inside the lambda expression. The local variable declared outside of a lambda expression may be final or effectively final.

 

interface MyInter { public String greet(String s); } public class Main { public static void main(String[] args) { String ob = "Hello Potter"; MyInter ob2 = (str) ->{ return ob+", "+str; }; System.out.println(ob2.greet("Himanshu")); } }

Output

Hello Potter, Himanshu

Instance Variables

Instance variables are non-static variables defined in a class outside any method, constructor, or block.  Constructor or block. Each instantiated object creates its own separate copy or instance variable. We can also access the instance variable using the lambda expression.

 

Program

interface MyInter { void print(); } public class FirstClass { int a; FirstClass(int x) { this.a = x; } void show() { MyInter t = () -> { System.out.println("a = "+ a); }; t.print(); } public static void main(String arg[]) { FirstClass ob = new FirstClass(19); ob.show(); } }

Output 

a = 19

Static Variables

In Java, a static variable belongs to a class and is only initialized once during execution. It is a class that is a specific variable, not an object-specific variable (instance). We can also access the static variable using the lambda expression. This is unsurprising, given the static variable can be accessed from anywhere in a Java  application.

 

Program

interface MyInter { void print(); } class FirstClass { static int b = 534; void show() { MyInter ob = () -> { System.out.println("b =  "+ b); }; ob.print(); } } public class Main{ public static void main(String arg[]) { FirstClass ob = new FirstClass(); ob.show(); } }

Output

b =  534

Advantages of Lambda Expression

There are many advantages of lambda expression. Let’s see the advantages:

 

  • Enhanced Readability: Lambda expression simplifies source code and makes it easier to read and understand.

 

  • Increased Flexibility: It provides flexibility in defining and using behavior dynamically for callback event handling.

 

  • Encapsulation of behavior: We can pass and encapsulate behavior, making code more customizable and extensible.

 

  • Increased Flexibility: It provides flexibility in defining and using behavior dynamically for callbacks, event handling, and other scenarios.

Disadvantages of Lambda Expression

Lambda expression also has some disadvantages. Let’s discuss the disadvantages one by one.

 

  • Limited Debugging Information: Lambda expression can make debugging more challenging, as the stack traces may be less informative than traditional anonymous classes.

 

  • Increased Complexity in Some Cases: Lambda expressions make the code more complicated when the developer is unfamiliar with Lamda’s expression.

 

  • Learning Curve: Developers new to functional programming and lambda expression may face a learning curve, which may initially impact productivity.

Important Points to Remember

  • A lambda expression is an implementation of a functional interface.
  • A lambda depression is an anonymous function that does not need to have a return type and input parameter data type.
  • We know the scope of the variable you are using in the lambda expression.

Conclusion

This article taught us about the lambda expression introduced in Java 8. It simplifies the syntax for creating these implementations, making the source code cleaner and more readable by eliminating the need for protracted anonymous class implementations.

 

By Understanding, we provide a more compact and flexible syntax, and the lambda expression facilitates a functional programming style where functions can be passed as arguments, tuned from methods, and assigned to variables, ultimately making the source code more expressive and easier to maintain.

FAQs
A functional interface has exactly one abstract method. It can have multiple default or static methods but only one abstract method.
A lambda expression can throw an unchecked exception, e.g., RuntimeException.They cannot throw a checked exception directly if a lambda expression needs to throw it.
A lambda expression defines an anonymous function that can be used to implement a functional interface concisely and readably.

Updated on September 17, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved