Java Lambda Expressions

Category : Java | Sub Category : Java 8 Features | By Prasad Bonam Last updated: 2020-09-30 04:38:43 Viewed : 1006


1. Java Lambda Expressions

Each lambda expression has two parts separated by an arrow token: the left hand side is our method arguments, and the right hand side is what we do with those arguments (business logic)

·        Lambda expressions are designed to allow code to be streamlined.

·        Lambdas expressions do not produce any extra classes the way nested classes do.

Syntax:

    1.     To use a single parameter and an expression:

        Parameter  -> expression

    2.     To use more than one parameter and an expression:

(parameter1, parameter2) -> expression

    3.     return a value and to use more complex operaions :

(parameter1, parameter2) -> { code block }


    

2. How can we  concat a string using lambda expression?

Source Code: JavaLambdaExpression.java

 

 public class JavaLambdaExpression {

     public static void main(String[] args) {

           //concating two strings

           String str = "*@!%$#?";

           StringFunction strFunction = (s) -> s + str;

           printFormatted("Expression "strFunction);

           //Square up two integers

           int i1 = 10; int i2 = 20;        

           IntegerFunction squareFunc  = (i)->i1*i2;

           System.out.println("square "squareFunc.run(i1));           

     }

    

     public static void printFormatted(String str, StringFunction format) {

           String result = format.run(str);

           System.out.println(result);

     }

}

 

interface StringFunction {

     String run(String str);

}

interface IntegerFunction{

     int run(int i);

}

 

 

OutPut:

    Expression *@!%$#?

    square 200

Search
Related Articles

Leave a Comment: