{"id":48363,"date":"2017-05-15T00:42:56","date_gmt":"2017-05-14T19:12:56","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=48363"},"modified":"2017-06-05T17:43:20","modified_gmt":"2017-06-05T12:13:20","slug":"functional-programming-in-java8-using-lambda-expressions","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/functional-programming-in-java8-using-lambda-expressions\/","title":{"rendered":"Functional Programming in Java8 Using Lambda Expressions"},"content":{"rendered":"<p style=\"text-align: justify\"><span style=\"color: #000000\">Lambda expressions are the most talked\u00a0feature of Java 8. Lambda expressions drastically change the way we write the code in Java 8 as compared to what we used to, in older versions.\u00a0<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Let&#8217; understand what lambda expression is and how it works.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">At first, you could think about lambda expressions as a way of supporting <a title=\"Java Development\" href=\"http:\/\/www.tothenew.com\/java-development-services\">functional programming in Java<\/a>. Functional programming is a paradigm that allows programming using expressions i.e. declaring functions, passing functions as arguments and using functions as statements (rightly called expressions in Java8). If you want to learn more about why it is called Lambda expressions, you could try to understand what Lambda Calculus is.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">If you have worked on <a title=\"Groovy Development\" href=\"http:\/\/www.tothenew.com\/grails-application-development\">groovy<\/a> and any other programming language which supports functional programming, comprehending Lambda expressions shouldn&#8217;t be a big deal. However, there is more about Lambda expressions than just being methods getting passed along with other methods.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Consider the following example to know more about Lambda Expressions.\u00a0<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Suppose you have to write a program that welcomes you into a different world of programming language.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">A simple implementation could be as:<\/span><\/p>\n<p>[code lang=&#8221;java&#8221;]<br \/>\npublic class WelcomeToProgrammingWorld {<br \/>\n    public static void main(String[] args) {<br \/>\n        System.out.println(&quot;Welcome to world of Java Programming Language!&quot;);<br \/>\n    }<br \/>\n}<br \/>\n[\/code]<\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Now, what if I also need to welcome you in Groovy and Python. A simple code could be as below:<\/span><\/p>\n<p>[code lang=&#8221;java&#8221;]<br \/>\npublic class WelcomeToProgrammingWorld {<br \/>\n    public static void main(String[] args) {<br \/>\n        System.out.println(&quot;Welcome to world of Java Programming Language!&quot;);<br \/>\n\t\tSystem.out.println(&quot;Welcome to world of Groovy Programming Language!&quot;);<br \/>\n\t\tSystem.out.println(&quot;Welcome to world of Python Programming Language!&quot;);<br \/>\n    }<br \/>\n}<br \/>\n[\/code]<\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">It&#8217;s not a correct approach. You shall be thinking about writing some generic implementation. You either create some method as below:<\/span><\/p>\n<p>[code lang=&#8221;java&#8221;]<br \/>\npublic class WelcomeToProgrammingWorld {<br \/>\n    public static void main(String[] args) {<br \/>\n        welcomeToALanguage(&quot;Java&quot;);<br \/>\n        welcomeToALanguage(&quot;Groovy&quot;);<br \/>\n        welcomeToALanguage(&quot;Scala&quot;);<br \/>\n    }<br \/>\n    static void welcomeToALanguage(String language) {<br \/>\n        System.out.println(&quot;Welcome to world of &quot; + language + &quot;Programming Language&quot;);<br \/>\n    }<br \/>\n}<br \/>\n[\/code]<\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Though the code looks concise, we could write it as follows:<\/span><\/p>\n<p>[code lang=&#8221;java&#8221;]<br \/>\npublic class WelcomeToProgrammingWorld {<br \/>\n    public static void main(String[] args) {<br \/>\n        WelcomeToALanguage welcomeToALanguage = new WelcomeToALanguage();<br \/>\n        welcomeToALanguage.welcome(&quot;Java&quot;);<br \/>\n        welcomeToALanguage.welcome(&quot;Groovy&quot;);<br \/>\n        welcomeToALanguage.welcome(&quot;Scala&quot;);<br \/>\n    }<br \/>\n}<\/p>\n<p>interface Welcome {<br \/>\n    abstract void welcome(String string);<br \/>\n}<\/p>\n<p>class WelcomeToALanguage implements Welcome {<br \/>\n    @Override<br \/>\n    public void welcome(String language) {<br \/>\n        System.out.println(&quot;Welcome to world of &quot; + language + &quot;Programming Language&quot;);<br \/>\n    }<br \/>\n}<br \/>\n[\/code]<\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Notice that we now have an interface, Welcome which could have multiple implementations for different ways to welcome. We have created a concrete class WelcomeToALanguage implementing the Welcome interface. Still, the output remains same, but the code is more generic and allows more ways of welcoming.\u00a0<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Here, if you have to welcome something differently, you need to provide another implementation and so on.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Another solution here could be to use Anonymous inner class to avoid creating multiple concrete classes for various implementations.<\/span><\/p>\n<p>[code lang=&#8221;java&#8221;]<br \/>\npublic class WelcomeToProgrammingWorld {<br \/>\n    public static void main(String[] args) {<br \/>\n        Welcome welcomeToALanguage = new Welcome() {<br \/>\n            @Override<br \/>\n            public void welcome(String language) {<br \/>\n                System.out.println(&quot;Welcome to world of &quot; + language + &quot;Programming Language&quot;);<br \/>\n            }<br \/>\n        };<br \/>\n        welcomeToALanguage.welcome(&quot;Java&quot;);<br \/>\n        welcomeToALanguage.welcome(&quot;Groovy&quot;);<br \/>\n        welcomeToALanguage.welcome(&quot;Scala&quot;);<br \/>\n    }<br \/>\n}<\/p>\n<p>interface Welcome {<br \/>\n    abstract void welcome(String string);<br \/>\n}<br \/>\n[\/code]<\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">So, now we have a robust and generic code which allows <\/span>declaring<span style=\"color: #000000\"> and using different implementations with anonymous inner class.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Now, let us understand Lambda expression and its implementation in the\u00a0<\/span><span style=\"background-color: #f5f6f5;color: #000000\">above <\/span><span style=\"color: #000000\">example.\u00a0<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">An implementation for a method say :<\/span><\/p>\n<p>[code lang=&#8221;java&#8221;]<br \/>\n public void welcome(String language) {<br \/>\n       System.out.println(&quot;Welcome to world of &quot; + language + &quot;Programming Language&quot;);<br \/>\n }<br \/>\n[\/code]<\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">will look like below\u00a0<\/span>in<span style=\"background-color: #f5f6f5;color: #000000\">\u00a0a lambda expression:<\/span><\/p>\n<p>[code lang=&#8221;java&#8221;]<br \/>\n (String language) -&gt; {<br \/>\n        System.out.println(&quot;Welcome to world of &quot; + language + &quot;Programming Language&quot;);<br \/>\n }<br \/>\n[\/code]<\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">You may want to forget about the assignment to some reference variable for now (and compilation too).<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">If you notice the difference:-<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">1. We have removed access specifier and return type as is intuitive for compiler by method definition.\u00a0<\/span><br \/>\n<span style=\"color: #000000\">2. We have a new operator -&gt; which is called Lambda expression i.e. it&#8217;s the separator between input and output.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Rest of the code remains the same.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\"><strong>Rule 1:\u00a0<\/strong>If you have only one statement inside the expression, then you don&#8217;t need <\/span>curly<span style=\"color: #000000\"> braces. Hence, the above code would look like:<\/span><\/p>\n<p>[code lang=&#8221;java&#8221;]<br \/>\n(String language) -&gt; System.out.println(&quot;Welcome to world of &quot; + language + &quot;Programming Language&quot;);<br \/>\n[\/code]<\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">It is better than the actual method call.\u00a0<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">As you have only one parameter, you could remove brackets and input parameter type in the input argument which is very brief.<\/span><\/p>\n<p>[code lang=&#8221;java&#8221;]<br \/>\nlanguage -&gt; System.out.println(&quot;Welcome to world of &quot; + language + &quot;Programming Language&quot;);<br \/>\n[\/code]<\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Remember till now we have not discussed any reference variable to reference a Lambda expression.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">So, Java probably might have provided some new class like Function, but that&#8217;s not the case. Java says that to assign a lambda expression you need to have an interface with only one abstract method and the compiler will automatically detect and assign it to that Interface reference variable.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">An interface with a single method is known as a Functional Interface.\u00a0<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000;font-size: 1rem\">Let us now try to modify our code for the problem that we initially solved using interface Welcome.<\/span><\/p>\n<p>[code lang=&#8221;java&#8221;]<br \/>\npublic class WelcomeToProgrammingWorld {<br \/>\n    public static void main(String[] args) {<br \/>\n        Welcome welcomeToALanguage =  language -&amp;gt; System.out.println(&quot;Welcome to world of &quot; + language + &quot;Programming Language&quot;);<br \/>\n        welcomeToALanguage.welcome(&quot;Java&quot;);<br \/>\n        welcomeToALanguage.welcome(&quot;Groovy&quot;);<br \/>\n        welcomeToALanguage.welcome(&quot;Scala&quot;);<br \/>\n    }<br \/>\n}<br \/>\ninterface Welcome {<br \/>\n    abstract void welcome(String string);<br \/>\n}<br \/>\n[\/code]<\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">You can see that we haven&#8217;t declared any anonymous inner class, but declared only a Lambda expression assigned to Welcome&#8217;s reference variable, and output is the same, but the code is super crisp.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Several people on the web, hold an opinion that Lambda expression is an Anonymous inner class which is untrue. Anonymous inner class is an utterly different concept. A simple way to prove this is to print the object welcomeToALanguage&#8217;s reference when we are using an inner class and when we are using the lambda expression. The output will be for example;<\/span><\/p>\n<p style=\"text-align: justify\"><strong><span style=\"color: #000000\">java8.lambda.expressions.WelcomeToProgrammingWorld$1@14ae5a5\u00a0<\/span><\/strong><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">for inner class and;<\/span><\/p>\n<p style=\"text-align: justify\"><strong><span style=\"color: #000000\">java8.lambda.expressions.WelcomeToProgrammingWorld$$Lambda$1\/1096979270@682a0b20<\/span><\/strong><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">for the lambda expression.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">You can see a significant difference here. Though an anonymous inner class with one method is closer to a lambda expression and these expressions, appear like a syntactic sugar, but there is more underneath.\u00a0<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">One thing is sure that &#8220;Lambda expression seamlessly binds itself with the existing Java ecosystem.&#8221;<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Before winding up this blog, have a look at some examples of Lambda expression:<\/span><\/p>\n<p><strong>A lambda expression with no parameters<\/strong><\/p>\n<p>[code]<br \/>\n() -&gt; System.out.println(&quot;Hi!Lambda Expressions is great.&quot;);<br \/>\n[\/code]<\/p>\n<p><strong>A lambda expression with one parameter<\/strong><\/p>\n<p>[code]<br \/>\n(String s) -&gt; System.out.println(&quot;Hi!Lambda Expressions is great.&quot;+s);<br \/>\n[\/code]<\/p>\n<p><strong>Another lambda expression with one parameter<\/strong><\/p>\n<p>[code]<br \/>\ns -&gt; System.out.println(&quot;Hi!Lambda Expressions is great.&quot;+s);<br \/>\n[\/code]<\/p>\n<p><strong>A lambda expression with 2 parameters<\/strong> (Note parantesis is required for 2 or more params)<\/p>\n<p>[code]<br \/>\n(s1, s2) -&gt; System.out.println(&quot;Hi!Lambda Expressions is great.&quot; + s1 + s2);<br \/>\n[\/code]<\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Some of its advantages are enlisted below:\u00a0<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">1. Less boilerplate and more concise code.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">2. Enables functional programming. You could read more about Functional programming, Lambda Calculus and Monads to understand Lambda expressions and how these enable functional programming.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">3. Binds seamlessly with stream API &amp; existing Java ecosystem where implementation varies for different streams.<\/span><\/p>\n<p style=\"text-align: justify\"><span style=\"color: #000000\">Hope, you will now be able to understand a basic use and syntax of Lambda expressions. I would be writing about Type Inference and Java Functional Interface API for Lambda expressions soon.\u00a0<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Lambda expressions are the most talked\u00a0feature of Java 8. Lambda expressions drastically change the way we write the code in Java 8 as compared to what we used to, in older versions.\u00a0 Let&#8217; understand what lambda expression is and how it works. At first, you could think about lambda expressions as a way of supporting [&hellip;]<\/p>\n","protected":false},"author":119,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":32},"categories":[446,1994,1],"tags":[323,4594,4591,4844,1513,4581],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/48363"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/119"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=48363"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/48363\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=48363"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=48363"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=48363"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}