{"id":368,"date":"2014-06-22T19:01:00","date_gmt":"2014-06-22T19:01:00","guid":{"rendered":"http:\/\/www.java2blog.com\/?p=368"},"modified":"2024-02-16T18:21:09","modified_gmt":"2024-02-16T12:51:09","slug":"lambda-expressions-in-java-8","status":"publish","type":"post","link":"https:\/\/java2blog.com\/lambda-expressions-in-java-8\/","title":{"rendered":"Lambda Expressions in Java 8"},"content":{"rendered":"<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#1_Introduction\">1. Introduction<\/a><\/li><li><a href=\"#2_What_is_Functional_Interface\">2. What is Functional Interface?<\/a><\/li><li><a href=\"#3_Why_Lambda_Expressions\">3. Why Lambda Expressions?<\/a><\/li><li><a href=\"#4_What_is_Lambda_Expressions\">4. What is Lambda Expressions?<\/a><\/li><li><a href=\"#5_Structure_of_Lambda_Expressions\">5. Structure of Lambda Expressions<\/a><\/li><li><a href=\"#6_HelloWorld_Lambda_Expression_Example\">6. HelloWorld Lambda Expression Example<\/a><\/li><li><a href=\"#7_Conclusion\">7. Conclusion<\/a><\/li><\/ul><\/div>\n<h2><span id=\"1_Introduction\">1. Introduction<\/span><\/h2>\n<div><a href=\"https:\/\/java2blog.com\/java-8-tutorial\/\">Java 8<\/a> has introduced a new feature called Lambda expressions. This is considered to be major change for Java because it introduces a way of programming that is more about actions than the details of how things are done. Other languages such as <code>Scala<\/code> already have this feature so this is not new to programming world, it is new to Java.<\/div>\n<div><\/div>\n<div>In this article, we&#8217;re going to start from the basics and make it easy to understand what Lambda expressions are and why they are useful. Let&#8217;s begin by explaining what Functional Interfaces are, as they are key to understanding Lambda expressions.<\/div>\n<div dir=\"ltr\" style=\"text-align: left;\">\n<h2><span id=\"2_What_is_Functional_Interface\">2. What is Functional Interface?<\/span><\/h2>\n<div><a href=\"https:\/\/java2blog.com\/java-8-functional-interface-example\/\" target=\"_blank\" rel=\"noopener noreferrer\">Functional interfaces<\/a> are those interfaces that have only one <a href=\"https:\/\/java2blog.com\/abstraction-java-example\/\" target=\"_blank\" rel=\"noopener noreferrer\">abstract method<\/a> in it. It can have more than one default or <a href=\"https:\/\/java2blog.com\/static-keyword-in-java\/\" target=\"_blank\" rel=\"noopener noreferrer\">static<\/a> method and can override the method from <code>java.lang.object<\/code>. Let&#8217;s create a functional interface:<\/div>\n<div><\/div>\n<div>\n<pre name=\"code\" class=\"\">@FunctionalInterface\r\npublic interface Decorable {\r\n\r\n \/\/ one abstract method\r\n void decorateWithCurtains();\r\n\r\n \/\/ default method\r\n default void decorateWithPaints()\r\n {\r\n  System.out.println(\"Decorating using paints\");\r\n }\r\n\r\n \/\/ Overriding method of java.lang.Object\r\n @Override\r\n public int hashCode();\r\n\r\n}<\/pre>\n<\/div>\n<div><\/div>\n<div>Java can itself identify Functional Interface but we can also denote <a href=\"https:\/\/java2blog.com\/interface-in-java-with-example\/\" target=\"_blank\" rel=\"noopener noreferrer\">interface<\/a> as Functional Interface by annotating it with <code>@FunctionalInterface<\/code>.<\/div>\n<div><\/div>\n<div>Some popular Functional Interfaces are:<\/div>\n<ul>\n<li><a href=\"https:\/\/java2blog.com\/java-runnable-example\/\" target=\"_blank\" rel=\"noopener noreferrer\">java.lang.Runnable<\/a><\/li>\n<li>java.util.concurrent.Callable<\/li>\n<li>java.awt.event.ActionListener<\/li>\n<li><a href=\"https:\/\/java2blog.com\/comparator-in-java\/\" target=\"_blank\" rel=\"noopener noreferrer\">java.util.Comparator<\/a><\/li>\n<\/ul>\n<h2><span id=\"3_Why_Lambda_Expressions\">3. Why Lambda Expressions?<\/span><\/h2>\n<div>Let&#8217;s understand with help of Anonymous Comparator.<\/div>\n<p>Let&#8217;s say we need to sort list of movies by movie name:<br \/>\n<code>Movie.java<\/code><\/p>\n<pre name=\"code\" class=\"java\">package org.arpit.java2blog;\r\n\r\npublic class Movie {\r\n\r\n    String movieName;\r\n    long duration;\r\n\r\n    public Movie(String movieName, long duration) {\r\n        super();\r\n        this.movieName = movieName;\r\n        this.duration = duration;\r\n    }\r\n\r\n    \/\/ getters and setters\r\n}\r\n<\/pre>\n<p>Code to sort list of movies by name using <a href=\"https:\/\/java2blog.com\/comparator-in-java\/\" target=\"_blank\" rel=\"noopener noreferrer\">comparator<\/a><\/p>\n<div>\n<pre name=\"code\">    Movie m1=new Movie(\"Inception\",110);\r\n    Movie m2=new Movie(\"GodFather\",200);\r\n    Movie m3=new Movie(\"Forest Gump\",130);\r\n    Movie m4=new Movie(\"Avengers\",150);\r\n\r\n    List&lt;Movie&gt; listOfMovies = new ArrayList&lt;&gt;();\r\n    listOfMovies.add(m1);\r\n    listOfMovies.add(m2);\r\n    listOfMovies.add(m3);\r\n    listOfMovies.add(m4);\r\n\r\n    System.out.println(\"Before Sort by name : \");\r\n    for (int i = 0; i &lt; listOfMovies.size(); i++) {\r\n      Movie movie = (Movie) listOfMovies.get(i);\r\n      System.out.println(movie);\r\n\r\n    }\r\n    \/\/ Sort by movieName\r\n    \/\/ Anonymous Comparator\r\n    \/\/ old way\r\n    Collections.sort(listOfMovies, new Comparator&lt;Movie&gt;() {\r\n      @Override\r\n      public int compare(Movie o1, Movie o2) {\r\n        return o1.getMovieName().compareTo(o2.getMovieName());\r\n      }\r\n    });\r\n<\/pre>\n<\/div>\n<div><\/div>\n<div>The problem with Anonymous Comparator lies in its syntax. Each time we want to sort a list using a comparator, remembering the bulky syntax becomes necessary.<\/div>\n<div><\/div>\n<div>Generally, the main issue with Anonymous classes is their syntax; even for very simple operations, complex code is required. To address this, JDK introduced a new feature called Lambda Expressions. We will revisit this example after explaining lambda expressions to understand how they can simplify complex code.<\/div>\n<h2><span id=\"4_What_is_Lambda_Expressions\">4. What is Lambda Expressions?<\/span><\/h2>\n<div>Lambda expression represents an anonymous function. It comprises of a set of parameters, a lambda operator (-&gt;) and a function body . You can call it <code>function without name<\/code>.<\/div>\n<div><\/div>\n<div><b>The connection between Lambda Expression and Functional Interface:<\/b><\/div>\n<div><\/div>\n<div>One might wonder about the connection between the previously introduced functional interface and Lambda expressions. Lambda expressions can be applied to the abstract method of a functional interface, which is either implemented or instantiated anonymously.<\/div>\n<h2><span id=\"5_Structure_of_Lambda_Expressions\">5. Structure of Lambda Expressions<\/span><\/h2>\n<div>\n<pre class=\"lang:default decode:true \" title=\"Syntax of lambda expression\">(Argument List) -&gt;{expression;} or\r\n(Argument List) -&gt;{statements;}<\/pre>\n<div>So we can divide structure of Lambda expression to three parts:<\/div>\n<div><\/div>\n<div style=\"clear: both; text-align: justify;\"><img decoding=\"async\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2021\/09\/lambdaExpressionExample.jpg\" border=\"0\" \/><\/div>\n<p>&nbsp;<\/p>\n<ul>\n<li><b>Argument list or parameters<\/b>\n<ul>\n<li>Lambda expression can have zero or more arguments.\n<div class=\"content-box-purple\">()-&gt;{System.out.println(&#8220;Hello&#8221;)}; \/\/Without argument, will print hello<br \/>\n(int a)-&gt;{System.out.println(a)}; \/\/ One argument, will print value of a<br \/>\n(int a,int b)-&gt; {a+b};\/\/two argument, will return sum of these two integers<\/div>\n<\/li>\n<li>We can choose to not declare the type of arguments as it can be inferred from context.<\/li>\n<li style=\"list-style-type: none;\">\n<div class=\"content-box-green\">(a,b)-&gt;{a+b}; \/\/ two argument, will return sum of these two numbers<\/div>\n<\/li>\n<li>We can not declare one argument&#8217;s type and do not declare type for other argument.<\/li>\n<li style=\"list-style-type: none;\">\n<div class=\"content-box-red\">(int a,b)-&gt;{a+b}; \/\/ Compilation error<\/div>\n<\/li>\n<li>When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses\n<div class=\"content-box-blue\">a-&gt;{System.out.println(a)}; \/\/ Will print value of number a<\/div>\n<\/li>\n<\/ul>\n<\/li>\n<li><b>Array token (-&gt;)<\/b><\/li>\n<li><b>Body<\/b>\n<ul>\n<li><code>Body<\/code> can have expression or statements.<\/li>\n<li><span data-preserver-spaces=\"true\">If there is only one statement in the body, the curly brace is not needed, and return type of the anonymous function is the same as the body expression<\/span><\/li>\n<li><span data-preserver-spaces=\"true\">If there is more than one statement, then it should be in curly braces, and return type of the anonymous function is the same as the value return from the code block, <code>void<\/code> if nothing is returned.<\/span><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<div>Let&#8217;s look at some examples, focusing on initializing a <a href=\"https:\/\/java2blog.com\/java-thread-example\/\" target=\"_blank\" rel=\"noopener\">thread<\/a>, and now it will become apparent how lambda expressions can simplify coding:<\/div>\n<div>\n<pre name=\"code\">public class ThreadSample {\r\n\r\n public static void main(String[] args) {\r\n\r\n  \/\/ old way\r\n  new Thread(new Runnable() {\r\n\r\n   @Override\r\n   public void run() {\r\n    System.out.println(\"Thread is started\");\r\n   }\r\n  }).start();\r\n\r\n  \/\/ using lambda Expression\r\n  new Thread(()-&gt;System.out.println(\"Thread is started\")).start();\r\n }\r\n\r\n}<\/pre>\n<\/div>\n<div><\/div>\n<div><span data-preserver-spaces=\"true\">Let&#8217;s take another example of\u00a0<\/span><a class=\"editor-rtfLink\" href=\"https:\/\/java2blog.com\/comparator-in-java\/\" target=\"_blank\" rel=\"noopener\"><span data-preserver-spaces=\"true\">Comparator<\/span><\/a><span data-preserver-spaces=\"true\">, which we have seen in Anonymous\u00a0<\/span><a class=\"editor-rtfLink\" href=\"http:\/\/www.java2blog.com\/comparator-in-java\/\" target=\"_blank\" rel=\"noopener\"><span data-preserver-spaces=\"true\">Comparator in Java<\/span><\/a><span data-preserver-spaces=\"true\">. We will create a list of movies and sort it by movie name using trivial way and lambda expressions.<\/span><\/div>\n<div>\n<p>Create a class called<\/p>\n<pre class=\"lang:default decode:1 inline:1 \">Movie.java<\/pre>\n<\/div>\n<div>\n<pre name=\"code\" class=\"java\">package org.arpit.java2blog;\r\n\r\npublic class Movie {\r\n\r\n    String movieName;\r\n    long duration;\r\n\r\n    public Movie(String movieName, long duration) {\r\n        super();\r\n        this.movieName = movieName;\r\n        this.duration = duration;\r\n    }\r\n\r\n    public String getMovieName() {\r\n        return movieName;\r\n    }\r\n    public void setMovieName(String movieName) {\r\n        this.movieName = movieName;\r\n    }\r\n    public long getDuration() {\r\n        return duration;\r\n    }\r\n    public void setDuration(long duration) {\r\n        this.duration = duration;\r\n    }\r\n\r\n    @Override\r\n    public String toString() {\r\n        return \"Movie Name: \" + this.getMovieName() + \"|| \"\r\n        + \"Movie duration: \" + this.getDuration();\r\n\r\n    }\r\n}\r\n<\/pre>\n<\/div>\n<div>Create a main class called ComparatorMain.java<\/div>\n<div>\n<pre name=\"code\">package org.arpit.java2blog;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collections;\r\nimport java.util.Comparator;\r\nimport java.util.List;\r\n\r\npublic class ComparatorLambdaMain {\r\n\r\n  \/**\r\n   * @author Arpit Mandliya\r\n   *\/\r\n  public static void main(String[] args) {\r\n\r\n    Movie m1=new Movie(\"Inception\",110);\r\n    Movie m2=new Movie(\"GodFather\",200);\r\n    Movie m3=new Movie(\"Forest Gump\",130);\r\n    Movie m4=new Movie(\"Avengers\",150);\r\n\r\n    List&lt;Movie&gt; listOfMovies = new ArrayList&lt;&gt;();\r\n    listOfMovies.add(m1);\r\n    listOfMovies.add(m2);\r\n    listOfMovies.add(m3);\r\n    listOfMovies.add(m4);\r\n\r\n    System.out.println(\"Before Sort by name : \");\r\n    for (int i = 0; i &lt; listOfMovies.size(); i++) {\r\n      Movie movie = (Movie) listOfMovies.get(i);\r\n      System.out.println(movie);\r\n\r\n    }\r\n    \/\/ Sort by movieName\r\n    \/\/ Anonymous Comparator\r\n    \/\/ old way\r\n    Collections.sort(listOfMovies, new Comparator&lt;Movie&gt;() {\r\n      @Override\r\n      public int compare(Movie o1, Movie o2) {\r\n        return o1.getMovieName().compareTo(o2.getMovieName());\r\n      }\r\n    });\r\n\r\n    \/\/ Using lambda expression\r\n    Collections.sort(listOfMovies, (o1, o2) -&gt; o1.getMovieName().compareTo(o2.getMovieName()));\r\n\r\n    System.out.println(\"After Sort by name: \");\r\n    for (int i = 0; i &lt; listOfMovies.size(); i++) {\r\n      Movie movie = (Movie) listOfMovies.get(i);\r\n      System.out.println(movie);\r\n    }\r\n  }\r\n}\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"content-box-purple\">Before Sort by name :<br \/>\nMovie Name: Inception|| Movie duration: 110<br \/>\nMovie Name: GodFather|| Movie duration: 200<br \/>\nMovie Name: Forest Gump|| Movie duration: 130<br \/>\nMovie Name: Avengers|| Movie duration: 150<br \/>\nAfter Sort by name:<br \/>\nMovie Name: Avengers|| Movie duration: 150<br \/>\nMovie Name: Forest Gump|| Movie duration: 130<br \/>\nMovie Name: GodFather|| Movie duration: 200<br \/>\nMovie Name: Inception|| Movie duration: 110<\/div>\n<\/div>\n<div><\/div>\n<div>As can be seen here, a lambda expression has been used for the Comparator. Instead of writing an Anonymous Comparator, the expression has been simplified significantly.<\/div>\n<div style=\"clear: both; text-align: justify;\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2021\/09\/LambdaExpressionExplaination.jpg\" width=\"640\" height=\"144\" border=\"0\" \/><\/div>\n<div>Thus, the arguments <code>o1<\/code> and <code>o2<\/code> were passed without specifying their types, as these can be inferred from the context. Since there is only one statement, there is no need to enclose it in curly braces.<\/div>\n<h2><span id=\"6_HelloWorld_Lambda_Expression_Example\">6. HelloWorld Lambda Expression Example<\/span><\/h2>\n<div>Create an Interface Called HelloWorld<\/div>\n<div>\n<pre name=\"code\">package org.arpit.java2blog;\r\n\r\n   public interface HelloWorld {\r\n       void sayHello();\r\n}\r\n\r\n<\/pre>\n<\/div>\n<div>Create a class called HelloWorldMain<\/div>\n<div>\n<pre name=\"code\">package org.arpit.java2blog;\r\n\r\npublic class HelloWorldMain {\r\n\r\n public static void main(String args[])\r\n {\r\n     \/\/ Lambda Expression\r\n     HelloWorld helloWorld=()-&gt;System.out.println(\"Hello using Lambda Expression\");\r\n    helloWorld.sayHello();\r\n }\r\n}<\/pre>\n<\/div>\n<div>Run above program you will get the following output:<\/div>\n<div>\n<div class=\"content-box-red\">Hello using Lambda Expression<\/div>\n<\/div>\n<\/div>\n<div dir=\"ltr\" style=\"text-align: left;\">\n<div>\n<h2><span id=\"7_Conclusion\">7. Conclusion<\/span><\/h2>\n<div>In this guide, we took a beginner-friendly look at Lambda expressions in Java. We started with what Functional Interfaces are and then moved on to what Lambda expressions are and how they make coding simpler and cleaner. For example, we saw how they can make sorting a list of movies or creating a new thread much easier than the old ways in Java. With Lambda expressions, you don&#8217;t have to write a lot of code for simple tasks. By the end of this article, you should have a basic understanding of Lambda expressions and how they can help you write better Java code. As you keep practicing and using them, you&#8217;ll see how handy and powerful they can be!<\/div>\n<div><\/div>\n<\/div>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Table of Contents1. Introduction2. What is Functional Interface?3. Why Lambda Expressions?4. What is Lambda Expressions?5. Structure of Lambda Expressions6. HelloWorld Lambda Expression Example7. Conclusion 1. Introduction Java 8 has introduced a new feature called Lambda expressions. This is considered to be major change for Java because it introduces a way of programming that is more [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":12610,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[36],"tags":[222,223],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/368"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=368"}],"version-history":[{"count":8,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/368\/revisions"}],"predecessor-version":[{"id":26184,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/368\/revisions\/26184"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/12610"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=368"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=368"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=368"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}