{"id":1310,"date":"2022-02-27T06:38:10","date_gmt":"2022-02-27T06:38:10","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=1310"},"modified":"2022-02-27T06:38:10","modified_gmt":"2022-02-27T06:38:10","slug":"lambda-expressions","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/02\/27\/lambda-expressions\/","title":{"rendered":"Lambda Expressions"},"content":{"rendered":"\n<p>In this article, we will learn about Java lambda expression and the use of lambda expression with functional interfaces, generic functional interface, and stream API with the help of examples.<\/p>\n\n\n\n<p>The lambda expression was introduced first time in Java 8. Its main objective to increase the expressive power of the language.<\/p>\n\n\n\n<p>But, before getting into lambdas, we first need to understand functional interfaces.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"functional\">What is Functional Interface?<\/h2>\n\n\n\n<p>If a Java interface contains one and only one abstract method then it is termed as functional interface. This only one method specifies the intended purpose of the interface.<\/p>\n\n\n\n<p>For example, the&nbsp;<code>Runnable<\/code>&nbsp;interface from package&nbsp;<code>java.lang<\/code>; is a functional interface because it constitutes only one method i.e.&nbsp;<code>run()<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example 1: Define a Functional Interface in java<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.lang.FunctionalInterface;\n@FunctionalInterface\npublic interface MyInterface{\n    \/\/ the single abstract method\n    double getValue();\n}<\/code><\/pre>\n\n\n\n<p>In the above example, the interface MyInterface has only one abstract method getValue(). Hence, it is a functional interface.<\/p>\n\n\n\n<p>Here, we have used the annotation&nbsp;<code>@FunctionalInterface<\/code>. The annotation forces the Java compiler to indicate that the interface is a functional interface. Hence, does not allow to have more than one abstract method. However, it is not compulsory though.<\/p>\n\n\n\n<p>In Java 7, functional interfaces were considered as\u00a0Single Abstract Methods or\u00a0<strong>SAM<\/strong>\u00a0type. SAMs were commonly implemented with Anonymous Classes in Java 7.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example 2: Implement SAM with anonymous classes in java<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>public class FunctionInterfaceTest {\n    public static void main(String&#91;] args) {\n\n        \/\/ anonymous class\n        new Thread(new Runnable() {\n            @Override\n            public void run() {\n                System.out.println(\"I just implemented the Runnable Functional Interface.\");\n            }\n        }).start();\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><samp>I just implemented the Runnable Functional Interface.<\/samp><\/pre>\n\n\n\n<p>Here, we can pass an anonymous class to a method. This helps to write programs with fewer codes in Java 7. However, the syntax was still difficult and a lot of extra lines of code were required.<\/p>\n\n\n\n<p>Java 8 extended the power of a SAMs by going a step further. Since we know that a functional interface has just one method, there should be no need to define the name of that method when passing it as an argument. Lambda expression allows us to do exactly that.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"intro\">Introduction to lambda expressions<\/h2>\n\n\n\n<p>Lambda expression is, essentially, an anonymous or unnamed method. The lambda expression does not execute on its own. Instead, it is used to implement a method defined by a functional interface.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How to define lambda expression in Java?<\/h3>\n\n\n\n<p>Here is how we can define lambda expression in Java.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>(parameter list) -&gt; lambda body<\/code><\/pre>\n\n\n\n<p>The new operator (<code>-&gt;<\/code>) used is known as an arrow operator or a lambda operator. The syntax might not be clear at the moment. Let&#8217;s explore some examples,<\/p>\n\n\n\n<p>Suppose, we have a method like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>double getPiValue() {\n    return 3.1415;\n}<\/code><\/pre>\n\n\n\n<p>We can write this method using lambda expression as:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>() -&gt; 3.1415<\/code><\/pre>\n\n\n\n<p>Here, the method does not have any parameters. Hence, the left side of the operator includes an empty parameter. The right side is the lambda body that specifies the action of the lambda expression. In this case, it returns the value 3.1415.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"types\">Types of Lambda Body<\/h3>\n\n\n\n<p>In Java, the lambda body is of two types.<\/p>\n\n\n\n<p><strong>1. A body with a single expression<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>() -&gt; System.out.println(\"Lambdas are great\");<\/code><\/pre>\n\n\n\n<p>This type of lambda body is known as the expression body.<\/p>\n\n\n\n<p><strong>2. A body that consists of a block of code.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>() -&gt; {\n    double pi = 3.1415;\n    return pi;\n};<\/code><\/pre>\n\n\n\n<p>This type of the lambda body is known as a block body. The block body allows the lambda body to include multiple statements. These statements are enclosed inside the braces and you have to add a semi-colon after the braces.<\/p>\n\n\n\n<p><strong>Note<\/strong>: For the block body, you can have a return statement if the body returns a value. However, the expression body does not require a return statement.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"example\">Example 3: Lambda Expression<\/h2>\n\n\n\n<p>Let&#8217;s write a Java program that returns the value of Pi using the lambda expression.<\/p>\n\n\n\n<p>As mentioned earlier, a lambda expression is not executed on its own. Rather, it forms the implementation of the abstract method defined by the functional interface.<\/p>\n\n\n\n<p>So, we need to define a functional interface first.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.lang.FunctionalInterface;\n\n\/\/ this is functional interface\n@FunctionalInterface\ninterface MyInterface{\n\n    \/\/ abstract method\n    double getPiValue();\n}\n\npublic class Main {\n\n    public static void main( String&#91;] args ) {\n\n    \/\/ declare a reference to MyInterface\n    MyInterface ref;\n    \n    \/\/ lambda expression\n    ref = () -&gt; 3.1415;\n    \n    System.out.println(\"Value of Pi = \" + ref.getPiValue());\n    } \n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Value of Pi = 3.1415<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example,<\/p>\n\n\n\n<ul><li>We have created a functional interface named&nbsp;<var>MyInterface<\/var>. It contains a single abstract method named&nbsp;<code>getPiValue()<\/code><\/li><li>Inside the&nbsp;<var>Main<\/var>&nbsp;class, we have declared a reference to&nbsp;<var>MyInterface<\/var>. Note that we can declare a reference of an interface but we cannot instantiate an interface. That is,<br>&nbsp;<code>\/\/ it will throw an error MyInterface ref = new myInterface(); \/\/ it is valid MyInterface ref;<\/code><\/li><li>We then assigned a lambda expression to the reference.<code>ref = () -&gt; 3.1415;<\/code><\/li><li>Finally, we call the method&nbsp;<code>getPiValue()<\/code>&nbsp;using the reference interface. When<br>&nbsp;<code>System.out.println(\"Value of Pi = \" + ref.getPiValue());<\/code><\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"lambda-expression-parameters\">Lambda Expressions with parameters<\/h2>\n\n\n\n<p>Till now we have created lambda expressions without any parameters. However, similar to methods, lambda expressions can also have parameters. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>(n) -&gt; (n%2)==0<\/code><\/pre>\n\n\n\n<p>Here, the variable n inside the parenthesis is a parameter passed to the lambda expression. The lambda body takes the parameter and checks if it is even or odd.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example 4: Using lambda expression with parameters<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@FunctionalInterface\ninterface MyInterface {\n\n    \/\/ abstract method\n    String reverse(String n);\n}\n\npublic class Main {\n\n    public static void main( String&#91;] args ) {\n\n        \/\/ declare a reference to MyInterface\n        \/\/ assign a lambda expression to the reference\n        MyInterface ref = (str) -&gt; {\n\n            String result = \"\";\n            for (int i = str.length()-1; i &gt;= 0 ; i--)\n            result += str.charAt(i);\n            return result;\n        };\n\n        \/\/ call the method of the interface\n        System.out.println(\"Lambda reversed = \" + ref.reverse(\"Lambda\"));\n    }\n\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>ambda reversed = adbmaL<\/samp><\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"generic\">Generic Functional Interface<\/h2>\n\n\n\n<p>Till now we have used the functional interface that accepts only one type of value. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@FunctionalInterface\ninterface MyInterface {\n    String reverseString(String n);\n}<\/code><\/pre>\n\n\n\n<p>The above functional interface only accepts\u00a0<code>String<\/code>\u00a0and returns\u00a0<code>String<\/code>. However, we can make the functional interface generic, so that any data type is accepted. If you are not sure about generics, visit\u00a0Java Generics.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example 5: Generic Functional Interface and Lambda Expressions<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ GenericInterface.java\n@FunctionalInterface\ninterface GenericInterface&lt;T&gt; {\n\n    \/\/ generic method\n    T func(T t);\n}\n\n\/\/ GenericLambda.java\npublic class Main {\n\n    public static void main( String&#91;] args ) {\n\n        \/\/ declare a reference to GenericInterface\n        \/\/ the GenericInterface operates on String data\n        \/\/ assign a lambda expression to it\n        GenericInterface&lt;String&gt; reverse = (str) -&gt; {\n\n            String result = \"\";\n            for (int i = str.length()-1; i &gt;= 0 ; i--)\n            result += str.charAt(i);\n            return result;\n        };\n\n        System.out.println(\"Lambda reversed = \" + reverse.func(\"Lambda\"));\n\n        \/\/ declare another reference to GenericInterface\n        \/\/ the GenericInterface operates on Integer data\n        \/\/ assign a lambda expression to it\n        GenericInterface&lt;Integer&gt; factorial = (n) -&gt; {\n\n            int result = 1;\n            for (int i = 1; i &lt;= n; i++)\n            result = i * result;\n            return result;\n        };\n\n        System.out.println(\"factorial of 5 = \" + factorial.func(5));\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Lambda reversed = adbmaL\nfactorial of 5 = 120<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have created a generic functional interface named&nbsp;<var>GenericInterface<\/var>. It contains a generic method named&nbsp;<code>func()<\/code>.<\/p>\n\n\n\n<p>Here, inside the Main class,<\/p>\n\n\n\n<ul><li><code>GenericInterface&lt;String&gt; reverse<\/code>&nbsp;&#8211; creates a reference to the interface. The interface now operates on&nbsp;<code>String<\/code>&nbsp;type of data.<\/li><li><code>GenericInterface&lt;Integer&gt; factorial<\/code>&nbsp;&#8211; creates a reference to the interface. The interface, in this case, operates on the&nbsp;<code>Integer<\/code>&nbsp;type of data.<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"stream\">Lambda Expression and Stream API<\/h2>\n\n\n\n<p>The new\u00a0java.util.stream\u00a0package has been added to JDK8 which allows java developers to perform operations like search, filter, map, reduce, or manipulate collections like\u00a0<code>Lists<\/code>.<\/p>\n\n\n\n<p>For example, we have a stream of data (in our case a&nbsp;<code>List<\/code>&nbsp;of&nbsp;<code>String<\/code>) where each string is a combination of country name and place of the country. Now, we can process this stream of data and retrieve only the places from Nepal.<\/p>\n\n\n\n<p>For this, we can perform bulk operations in the stream by the combination of Stream API and Lambda expression.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example 6: Demonstration of using lambdas with the Stream API<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.ArrayList;\nimport java.util.List;\n\npublic class StreamMain {\n\n    \/\/ create an object of list using ArrayList\n    static List&lt;String&gt; places = new ArrayList&lt;&gt;();\n\n    \/\/ preparing our data\n    public static List getPlaces(){\n\n        \/\/ add places and country to the list\n        places.add(\"Nepal, Kathmandu\");\n        places.add(\"Nepal, Pokhara\");\n        places.add(\"India, Delhi\");\n        places.add(\"USA, New York\");\n        places.add(\"Africa, Nigeria\");\n\n        return places;\n    }\n\n    public static void main( String&#91;] args ) {\n\n        List&lt;String&gt; myPlaces = getPlaces();\n        System.out.println(\"Places from Nepal:\");\n        \n        \/\/ Filter places from Nepal\n        myPlaces.stream()\n                .filter((p) -&gt; p.startsWith(\"Nepal\"))\n                .map((p) -&gt; p.toUpperCase())\n                .sorted()\n                .forEach((p) -&gt; System.out.println(p));\n    }\n\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Places from Nepal:\nNEPAL, KATHMANDU\nNEPAL, POKHARA<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, notice the statement,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>myPlaces.stream()\n        .filter((p) -&gt; p.startsWith(\"Nepal\"))\n        .map((p) -&gt; p.toUpperCase())\n        .sorted()\n        .forEach((p) -&gt; System.out.println(p));<\/code><\/pre>\n\n\n\n<p>Here, we are using the methods like&nbsp;<code>filter()<\/code>,&nbsp;<code>map()<\/code>&nbsp;and&nbsp;<code>forEach()<\/code>&nbsp;of the Stream API. These methods can take a lambda expression as input.<\/p>\n\n\n\n<p>We can also define our own expressions based on the syntax we learned above. This allows us to reduce the lines of code drastically as we saw in the above example.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn about Java lambda expression and the use of lambda expression with functional interfaces, generic functional interface, and stream API with the help of examples. The lambda expression was introduced first time in Java 8. Its main objective to increase the expressive power of the language. But, before getting into [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[597],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1310"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=1310"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1310\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=1310"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=1310"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=1310"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}