Skip to content
  • Facebook
GeekCer Logo

GeekCer

The geek's Coding education and Review centre

  • Home
  • Tutorials
    • Java
    • Servlet
    • JSP
    • Python
    • C Tutorial
    • Spring
    • Spring Boot
    • MongoDB
    • Hibernate
    • Data Structure
  • General Knowledge
  • Biography
  • Grammar
  • Festival (त्योहार)
  • Interview
  • Differences
  • Important
  • Toggle search form

Home » Java » Lambda Expression in Java 8 | Functional Interface | Example

  • Servlet Tutorial
    Servlet Tutorial Servlet
  • Binary search in Data structures In C (Recursive and Iterative)
    Binary search algorithm in C, Recursive, Iterative, examples Data Structure
  • Rabindranath Tagore Biography in Hindi, Poems, Birthday
    Rabindranath Tagore Biography in Hindi, Title of Gurudev Biography
  • Collections in Java
    Collections in Java Java
  • Difference between Runnable and Callable in Java
    Difference between Runnable and Callable in Java Differences
  • Java ArrayList
    Java ArrayList Java
  • List Of National Animals Of Countries
    List Of National Animals Of Countries General Knowledge
  • Design Pattern in Software Engineering
    Design Pattern in Software Engineering Important

Lambda Expression in Java 8 | Functional Interface | Example

Posted on December 8, 2021June 17, 2022 By GeekCer Education No Comments on Lambda Expression in Java 8 | Functional Interface | Example
Lambda Expression in Java 8 | Functional Interface | Example

Lambda expressions aided the developer in simplifying the development process. The lambda expression is important feature of Java 8. This functionality is highly useful in collections for iterating and filtering the data.

It does not have a return type or even a method name, and it does not specify accessibility. Classes and objects are given less weight in lambda expressions. It’s sometimes referred to as anonymous methods.

What are the advantages of lambda expressions in Java? The Function interface is implemented by Lambda Expression, which saves a lot of code throughout the development process.  All you have to do now is write the implementation code.

Table of Contents

  • Characteristics of a Java 8 lambda expression
  • Java Lambda Expression in Java example
  • What is Functional Interface with example?
  • Example of Functional Interface in Java 8
  • In Java, how do you write a lambda expression?
  • Creating a Thread Using Lambda Expressions

Characteristics of a Java 8 lambda expression

What is the use of Lambda expressions in Java? Lambda expressions are used to simulate the functionality of an anonymous class without having to use a clustering implementation.

Basic syntax of lambda expression

parameter -> body // Single parameter

(parameter1, parameter2) -> expression // Multiple parameters
  • If you use Lambda Express then using type declaration is optional. The compiler will make the decision internally.
  • Using curly braces for a single statement is optional.
  • It is optional to use if you are using single parameter.
  • It is the compiler’s responsibility to return the value if the body contains a single expression. Using the return keyword is optional. But you need to use curly breaks to indicate that the expression is returning a value.

Java Lambda Expression in Java example

We’ll show you how to use a method that just displays one message. We’ll look at two examples in this section. One technique is to create a simple java method, while the other is to use a lambda expression to create the equivalent method.

public void show(){
    System.out.println("Hello, Geeks!");
} 

Equivalent Lambda Expression

()->{System.out.println("Hello, Geeks!");}

What is Functional Interface with example?

The idea of a functional interface, which contains just one abstract method, this feature comes in Java 8. If someone asks what a functional interface is? You might respond that it’s an interface with only one abstract method.

We need to use the annotation @FunctionalInterface to indicate that this is a functional interface.

@FunctionalInterface
public interface FunctionInterfaceDemo {
   void performAction();
} 

It will throw an exception if you try to write more than one method in a functional interface (if that interface is specified with @FunctionalInterface annotation).

Example of Functional Interface in Java 8

To use a lambda expression, we should first design a functional interface. A method can also take another functional interface reference as a parameter.

interface FunctionalInterfaceDemo{
	void performCalculation(double h, double w);
}

public class Rectangle {
	public static void main(String[] args) {
		FunctionalInterfaceDemo fi=(h, w)->{
			System.out.println("Area of Rectangle is "+ h * w);
		};
		fi.performCalculation(10, 20);
	}
}
Output:
Area of Rectangle is 200.0

In Java, how do you write a lambda expression?

The following are some examples of how to construct lambda expressions in Java.

The number of arguments in a expression might be zero, one, or more.

()->System.out.println("Hello Geeks, Lambda Expression");

It is not necessary for the programmer to specify the type of argument. If the compiler can determine the type of the argument,

(x, y)->System.out.println("Addition = "+(x + y));

We have to use commas to separate parameters.

(double x, double y) or (x, y)

When there is a no parameter we must use empty parenthesis.

()->System.out.println("Hello, World!");

We don’t need to use parentheses if the type of a single argument is known to the compiler.

(int n) -> return n;
n -> return n + 10;

We should encapsulate them in curly brackets if they have more than one statement in their body. When there is only one statement, it is optional to use curly braces.

()->{
	System.out.println("Statement 1");
	System.out.println("Statement 2"); 
 }
()->System.out.println("Only one Statement");

Creating a Thread Using Lambda Expressions

In this section we will look at an example of running a thread using lambda expressions.

In this example we have created two threads using Runnable interface. First thread is running without using expression and second thread is running using lambda expression.

public class LambdaExpressionThread{  
    public static void main(String[] args) {  
         
        Runnable runnable1 = new Runnable() {  
            public void run() {  
                System.out.println("This is thread 1");  
            }  
        };  
        Thread thread1 = new Thread(runnable1);  
        thread1.start();  
        
        // Example of thread using lambda expression
        Runnable runnable2 = () -> {  
                System.out.println("This is thread 2");  
        };  
        Thread thread2 = new Thread(runnable2);  
        thread2.start();  
    }  
}  
Output:
This is thread 1
This is thread 2

Click here to read Java 8 popular interview questions and answers

Recommended Articles

  • Stream’s map() examples in Java 8
  • Features in Java 11

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • More
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)

Also Read

Java Tags:How do you call a method using lambda expression?, How do you return a lambda expression in Java?, What is lambda expression in Java?, What is the equivalent Java code for lambda expression?, What is the type of lambda expression in Java 8?

Post navigation

Previous Post: Stack Vs Heap in Java | Memory Allocation Section in Java
Next Post: Concurrent collections in Java, details, advantages, examples

More Related Articles

Multithreading in java Multithreading in java, Thread, Runnable | Life Cycle of Thread Java
Java Operators Java Operators Java
Data Types in Java Data Types in Java Java
Difference between Interface and Abstract class Difference between Interface and Abstract class Differences
Fork/Join Framework in Java | RecursiveTask, RecursiveAction Fork/Join Framework in Java | RecursiveTask, RecursiveAction Java
Java LinkedList Java LinkedList Java

Related Posts

  • Multithreading in java
    Multithreading in java, Thread, Runnable | Life Cycle of Thread Java
  • Java Operators
    Java Operators Java
  • Data Types in Java
    Data Types in Java Java
  • Difference between Interface and Abstract class
    Difference between Interface and Abstract class Differences
  • Fork/Join Framework in Java | RecursiveTask, RecursiveAction
    Fork/Join Framework in Java | RecursiveTask, RecursiveAction Java
  • Java LinkedList
    Java LinkedList Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Java Home
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Keywords
  • Java Operators
  • Java If-else Statement
  • Java Switch
  • Java Loop
  • Java Arrays
  • Method Overloading in Java
  • Java OOP
  • Java Collections
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Multithreading in java
  • Thread Synchronization
  • Exception Handling
  • Java JDBC Driver
  • Java Database Connectivity steps
  • Lambda Expressions
  • Concurrent Collections

Recent Posts

  • Ohms law Definition, Formula, Statement | ओम का नियम
  • TCP/IP Model, Full Form, Layers and their Functions
  • OSI Model | 7 Layers of OSI Model in Computer network, Functions
  • Mockito Framework Tutorial for Unit testing | Mockito unit testing spring boot
  • Draupadi Murmu Biography In Hindi | द्रौपदी मुर्मू की जीवनी
  • Chemical Properties of Matter examples (Element, Compound and Mixture)
  • CascadeType in Hibernate and JPA | JPA Cascading Operations
  • States of Matter | Physical Properties of Matter (Solid, Liquid, Gas)
  • Servlet Tutorial
    Servlet Tutorial Servlet
  • Binary search in Data structures In C (Recursive and Iterative)
    Binary search algorithm in C, Recursive, Iterative, examples Data Structure
  • Rabindranath Tagore Biography in Hindi, Poems, Birthday
    Rabindranath Tagore Biography in Hindi, Title of Gurudev Biography
  • Collections in Java
    Collections in Java Java
  • Difference between Runnable and Callable in Java
    Difference between Runnable and Callable in Java Differences
  • Java ArrayList
    Java ArrayList Java
  • List Of National Animals Of Countries
    List Of National Animals Of Countries General Knowledge
  • Design Pattern in Software Engineering
    Design Pattern in Software Engineering Important
  • Java Tutorial
  • Servlet Tutorial
  • JSP Tutorial
  • Maven Tutorial
  • HTML Tutorial
  • Programs
  • Hindi/English Grammar
  • Difference Between ... and ...
  • HR Interview
  • Important Articles

Write to Us:
geekcer.code@gmail.com

  • About Us
  • Privacy and Policy
  • Disclaimer
  • Contact Us
  • Sitemap

Copyright © GeekCer 2022 All Rights reserved