EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Java 8 Tutorial Java 8 Lambda
Secondary Sidebar
Java 8 Tutorial
  • Java 8 basic
    • Java 8 forEach
    • Java 8 Documentation
    • Java 8 Method Reference
    • Java 8 List to Map
    • Java 8 Parallel Stream
    • Java 8 Functional Interface
    • Java 8 API
    • Java 8 Lambda
    • Java 8 Comparator
    • Java 8 Group By
    • Java 8 Predicate
    • Java 8 Default Methods
    • Java 8 Thread
    • Java 8 HashMap
    • Java 8 Read File
    • Java 8 OpenJDK
    • Java 8 Stream Filter
    • Java 8 Interface

Java 8 Lambda

Introduction to Java 8 Lambda

Java 8 introduced a new feature called lambda or closures or an anonymous method. They are similar to functions but do not need a name as in functions. They take in parameters and may return a value. They can be implemented within the body of functions.

Java 8 Lambda

Key Takeaways

  • What are lambda expressions and its syntax.
  • Lambda expression can have zero to multiple parameters.
  • Example of using lambda expression with and without parameter.
  • Lambda expression as a parameter to a function.
  • Optional syntax in lambda parameter.

What is Java 8 Lambda?

Java 8 lambda expressions enable the creation of a function without a class. A simple expression does not have variables, assignments, or conditional statements. A return statement is required if the lambda expression is required to return a value.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

A simple example of a lambda expression is parameter-> expression.

Lambda expression implements a functional interface which is an interface with only one abstract method. A functional interface is declared through annotation @FunctionalInterface.

Examples of functional interface:

  • java.lang.Runnable
  • java.util.function.Consumer
  • java.util.Comparator
  • java.util.concurrent.Callable

Java 8 Lambda Expressions

Lambda expressions have a parameter, an arrow, and a code block referred to as an expression or body.

There can be zero to multiple parameters depending on the requirements. The use of Lambda Expression helps in reducing the code size.

  • Multiple parameters
    (parameter1, parameter2, parameter3, parameter4) -> expression
  • Complex logic is applied within curly braces.
    (parameter1, parameter2) -> {code block}
  • one parameter
    parameter -> expression
  • Zero parameter
    () -> expression

Examples of Java 8 Lambda

Given below are the examples mentioned:

Example #1

Lambda expression as parameters to a function.

forEach function of the class ArrayList is using lambda expression as its parameter in the below example.

Code:

import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> str = new ArrayList<String>();
str.add("I am happy.");
str.add("I am responsible. ");
str.add("I am alert.");
str.forEach( (n) -> { System.out.println(n); } );
}
}

Output:

Java 8 Lambda - forEach function

Example #2

Example of Lambda expression without parameter and how it would be implemented if lambda expression is not used.

Here we have declared an interface Animator which has two public functions. The animate function is taking no parameter.

With lambda expression:

Code:

interface Animator{
public void animate();
}
public class Main{
public static void main(String[] args) {
int radius=10;
Animator a2=()->{
System.out.println("Animation "+radius);
};
a2.animate();
}
}

Output:

Animation 10

Without lambda expression:

Code:

interface Animator{
public void animate();
}
public class Main{
public static void main(String[] args) {
int radius =10;
Animator a1=new Animator(){
public void animate(){System.out.println("Animation "+ radius);}
};
a1.animate();
}
}

Output:

Without lambda expression

Example #3

Example of Lambda expression with one parameter. The animate2D function is taking one parameter in the interface Animator.

Code:

interface Animator{
public String animate2d(Integer width);
}
public class figurine{
public static void main(String[] args) {
// Lambda expression with single parameter.
Animator s1=(width)->{
return "The width is, "+width;
}; // End of Lambda Expression
System.out.println(s1.animate2d(10));
}
}

Output:

One parameter in interface Animator

Scope

The lambda expression is an anonymous function, or you can say a classless function. Therefore it is not limited to the scope of class which otherwise would be the case. The lambda expression helps to use code as data. That means a code block can be passed as data to function.

It enables on-demand execution and can be passed as an object.

Scope of lambda variables:

  • The lambda expression should not declare a parameter with the same name as the local variable outside the lambda block of code. It will be similar to declare two variables with the same name in a function.
  • A variable that has a constant value at compile time can only be used in a lambda expression.

For example:

Code:

public class Main{
public static void textPrint(String text, int count) {
//Lambda Expression
Runnable r = () -> {
while (count > 0) {
count--; // Error:
System.out.println(text);
}
}; //End of Lambda Expression
}
}

Output:

Java 8 Lambda Variables

Here, we get the error because the variable count is being mutated in a lambda expression.

The code will work if the variable count is not inside the lambda expression. For example, in the following code, we are printing the text EduCBA two times.

Code:

public class Main {
public static void main(String[] args) {
int count =2;String text=" EduCBA ";
//Lambda Expression
Runnable r = () -> System.out.println(text);
//End of Lambda Expression
while (count > 0) {
count--;
r.run();
}
}
}

Output:

variable count is not inside

Lambda Operator

It is an arrow that separates the parameter list on the left from the code block on the right of the lambda expression.

Different ways of writing a lambda expression:

  • Type declaration: It is optional as the parameter type can be inferred by the compiler by the parameter value.
  • Parenthesis enclosing parameter: It is optional for the declaration of a single parameter. In Example (c) above, the parameter width can be declared without parenthesis.
Animator s1=width->{
return "The width is, "+width;
};
  • Curly braces in code block: If the expression body consists of a single statement, then curly braces are optional.
  • Keyword return: It is optional if the expression body has a single return value. Curly braces indicate to the compiler that the expression has value to returns.

For example:

Code:

interface SubIt{
int minus(int a,int b);
}
public class Substraction {
public static void main(String[] args) {
// Lambda expression 1
// without keyword return
SubIt ad1=(a,b)->(a-b);
System.out.println(ad1.minus(10,20));
// Lambda expression 2
// with keyword return .
SubIt ad2=(int a,int b)->{
return (a-b);
};
System.out.println(ad1.minus(1,22));
System.out.println(ad2.minus(978,900));
}
}

Output:

Writing Java 8 Lambda

Conclusion

The introduction of lambda expression has changed the way programmers design their projects. There is no need to declare a class to define a single function and hence reducing the code and the need to keep track of the class in documentation. With lambda expression, blocks of code can be defined, passed, and stored for later execution and can be treated as an object making functional programming easier to implement.

Recommended Articles

This is a guide to Java 8 Lambda. Here we discuss the introduction, java 8 lambda expressions, examples, scope, and operator. You may also have a look at the following articles to learn more –

  1. Text File in Java
  2. Java 8 forEach
  3. Java for Automation Testing
  4. Java SFTP
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more