Skip to main content

Lambda Expression in Java 8 with examples | Programming Blog

Lambda Expression in Java

What is Lambda Expression in Java 8?

In java, Lambda expression are introduced in java 8. Lambda is first step for Functional Programming.

Lambda expression is just anonymous function or we can say nameless function.
 
Java lambda expression are used to implement simple callback, event listener or functional programming with java stream API.
Lambda expression is really helpful in collection library. It helps filter, iterate and get data from collection.

Lambda expression is provide implementation of an interface which has Functional interface.
Lambda expression is treated as function in java.
 
We can say it is Lambda expression if function follows following condition :-
  1. Function does not have name
  2. Function does not have return type
  3. Function does not have modifiers

Why we need Lambda Expression in Java?

-> To enable Functional programming we need Lambda expression in Java. 
 
So, why we must use lambda expression. because of simple following advantage.
  • Less code compare than simple code.
  • To provide implementation of functional interface.
  • Lambda expression can be created without belong to any class.
  • Lambda expression enable to treat functionality as method argument.
So this are main functionality of lambda expression. so now lets see syntax of lambda expression.
(Arguments list) -> { Body of function}

So let's see example, how we can use lambda expression in our java code. First we try to create simple java method and after how we can achieve using Lambda expression.
 
Without Lambda expression :-
// Without parameters
public void method() {
    System.out.println("This is method without lambda expression");
}
 
// With parameters
public void addMethod(int a, int b) {
     System.out.println(a+b);
}
 
With Lambda expression :-
// Without parameters 
() ->  System.out.println("This is method with lambda expression");
 
// With parameters 
(int a, int b) ->  System.out.println(a+b);
    
If there is 1 parameter in method, parenthesis is optional but in 2 or more parameters we must use parenthesis. 

Some key parameters for Lambda expression :-
  • We can use lambda expression on any number of arguments.
  • For one argument lambda expression parenthesis is optional but for all other it is compulsory.
  • If lambda expression function body contains one line then curly braces is optional.
  • If lambda expression function body contains more than one line then curly braces is compulsory.

Example 1 : Java code without lambda expression

public interface LambdaExpression {
    public void programming();
}

public class LambdaExpressionImplementation implements LambdaExpression{

    @Override
    public void programming() {
        System.out.println("Implementation of interface");
    }

    public static void main(String args[]) {
        // creating object
        LambdaExpressionImplementation obj = new LambdaExpressionImplementation();
       
        
// calling programming method of  LambdaExpression
        obj.programming();
    }
}

Example 2 : Java code with lambda expression

public interface LambdaExpression {
    public void programming();
}

public class LambdaExpressionImplementation implements LambdaExpression{
   
    public static void main(String args[]) {
       
        LambdaExpression obj = () -> {
            System.out.println("Implementation of interface");
        };
       
        obj.programming();
    }
}


You can see how much simple and easy to implement method using lambda expression.
Now we see how can we implement lambda expression using one parameter.

Example 3 : Lambda expression with one parameter

public interface LambdaExpression {   
    public void programming(String languageName);
}

public class LambdaExpressionImplementation implements LambdaExpression{
   
    public static void main(String args[]) {
        
        // One parameter with paranthesis.
        LambdaExpression expression1 = (languageName) -> {
            System.out.println("Progarmming language :- " + languageName);
        };
       
        expression1.programming("Java");

        // One parameter without parathesis.       
        LambdaExpression expression2 = languageName -> {
            System.out.println("Programming language :- " +languageName );
        };
       
        expression2.programming("Python");
    }
}

Output :-
Progarmming language :- Java
Programming language :- Python

We can also write lambda expression without paranthesis if we only have one parameter like in above example.

Now lets see how lambda expression used with two parameter.

Example 4 : Lambda expression with two parameter

public interface LambdaExpression {
    public int sumOfTwoNumber(int number1, int number2);
}

public class LambdaExpressionImplementation implements LambdaExpression{
   
    public static void main(String args[]) {
       
        //with datatype in expression
        LambdaExpression expression1 = (int number1 ,int number2) ->
            (number1 + number2);
        System.out.println("Sum of two numbers : "+
            expression1.sumOfTwoNumber(5, 5));
       
        //without datatype in expression
        LambdaExpression expression2 = (number1 ,number2) ->
            (number1 + number2);
        System.out.println("Sum of two numbers : "+
            expression2.sumOfTwoNumber(10, 10));
       
    } 
}
 
Output :-
Sum of two numbers : 10
Sum of two numbers : 20


We had seen lambda expression with one parameter and with two parameter now we see how to use lambda expression with loop. it is very simple to use lambda with list.

Example 5 : Lambda expression with for loop

public class LambdaExpression{

    public static void main(String args[]) {
   
        //create list and add values into list
        List<String> programmingLanguages = new ArrayList<>();
        programmingLanguages.add("Java");
        programmingLanguages.add("JavaScript");
        programmingLanguages.add("Python");
        programmingLanguages.add("DotNet");
       
        // Print values with simple foreach loop
        for (String language : programmingLanguages) {
            System.out.println(language);
        }
       
        // Print values using lambda expression
        programmingLanguages.forEach(language ->
            System.out.println(language)
        );
    }
  
}

Now lets see how to print odd and even number using lambda expression.

Example 6 : Print odd and even numbers using lambda expression

public class LambdaExpression{

    public static void main(String args[]) {
   
       List<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);
        numbers.add(6);
       
        // Print even numbers from list
        numbers.forEach(number -> {
            if (number % 2 == 0) {
                System.out.println("Even Numbers : "+ number);
            }
        });
       
        // Print Odd number from list
        numbers.forEach(number -> {
            if (number % 2 != 0) {
                System.out.println("Odd Numbers : "+ number);
            }
        });
    }
  
}

output :-
Even Numbers : 2
Even Numbers : 4
Even Numbers : 6
Odd Numbers : 1
Odd Numbers : 3
Odd Numbers : 5


So it is easy to code in java using lambda expression. this is great feature that add in java 8.
If you want to learn more about lambda expression here is link :-


You can learn more java 8 features in following article.


Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last