{"id":4280,"date":"2021-05-15T09:14:52","date_gmt":"2021-05-15T09:14:52","guid":{"rendered":"https:\/\/codethataint.com\/blog\/?p=4280"},"modified":"2023-12-02T15:36:29","modified_gmt":"2023-12-02T15:36:29","slug":"how-lambda-expression-works-internally","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/how-lambda-expression-works-internally\/","title":{"rendered":"How Lambda Expression Works Internally"},"content":{"rendered":"<p><strong class=\"ctaHeader3\">When to use Lambda Expressions<\/strong><br \/>\nIf you have a functional Interface which has only one Abstract Method then we can use Lambda Expression at the Class which implements the  functional interface<br \/>\nand provides the method definition for the abstract method in Functional Interface.<\/p>\n<ol>\n<li>We have a Function Interface Printable with abstract method print<\/li>\n<li>Two classes implements functional Interface &#8211; DailyReport and MothlyReport. They provide the method definition for Print() method in Printable Interface<\/li>\n<li>GenerateReport class has a downloadReport method which takes the Printable Type as argument<\/li>\n<li>DownloadReport Class we use the Printable reference and call the exact implementation by passing as argument<\/li>\n<\/ol>\n<p><strong>Printable.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n@FunctionalInterface\r\npublic interface Printable {\r\n    public void print();\r\n}\r\n<\/pre>\n<p><strong>DailyReport.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class DailyReport implements Printable {\r\n    @Override\r\n    public void print() {\r\n        System.out.println(&quot;Printing Report in Daily Format&quot;);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>MonthlyReport.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class MonthlyReport implements Printable {\r\n    @Override\r\n    public void print() {\r\n        System.out.println(&quot;Printing Report in Monthly Format&quot;);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>GenerateReport.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class GenerateReport {\r\n    public static void downloadReport(Printable printable){\r\n        printable.print();\r\n    }\r\n}\r\n<\/pre>\n<p><strong class=\"ctaHeader3\">Without Lambda Expression<\/strong><br \/>\n<strong>DownloadReport.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class DownloadReport {\r\n    public static void main(String&#x5B;] args) {\r\n        GenerateReport objGenReport = new GenerateReport();\r\n        Printable objDailyReport = new DailyReport();\r\n        Printable objMonthlyReport = new MonthlyReport();\r\n\r\n        objGenReport.downloadReport(objDailyReport);\r\n        objGenReport.downloadReport(objMonthlyReport);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nPrinting Report in Daily Format\r\nPrinting Report in Monthly Format\r\n<\/pre>\n<p><strong class=\"ctaHeader3\">With Lambda Expression<\/strong><br \/>\nUsing Lambda expression we can pass method definition directly as parameter instead of using a class to extend interface and writing a method definition for the interface method<br \/>\n<strong>DownloadReport.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class DownloadReport {\r\n    public static void main(String&#x5B;] args) {\r\n        GenerateReport objGenReport = new GenerateReport();\r\n        objGenReport.downloadReport(() -&gt; System.out.println(&quot;Printing Report in Daily Format using Lambda Expr&quot;));\r\n\r\n        Printable mnthlyReport = () -&gt; System.out.println(&quot;Printing Report in Monthly Format using Lambda Expr&quot;);\r\n        objGenReport.downloadReport(mnthlyReport);     \r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nPrinting Report in Daily Format using Lambda Expr\r\nPrinting Report in Monthly Format using Lambda Expr\r\n<\/pre>\n<table class=\"table table-striped table-hover\">\n<tbody>\n<tr>\n<td><strong>With Lambda Expression<\/strong><\/td>\n<td><strong>Without Lambda Expression<\/strong><\/td>\n<\/tr>\n<tr>\n<td>We pass the method definition as Argument<\/td>\n<td>\n<ol>\n<li>Method Definition in MonthlyReport.java<\/li>\n<li>Method Definition in DailyReport.java<\/li>\n<li>Object creation for DailyReport and MonthlyReport<\/li>\n<\/ol>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Let&#8217;s take the below Example where we find the square of even numbers<\/p>\n<p><strong>ReduceEgs.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class ReduceEgs {\r\n    public static void main(String&#x5B;] args) {\r\n        List&lt;Integer&gt; arrNumbers = Arrays.asList(1,2,4,5,7,6);\r\n\r\n        arrNumbers.stream()\r\n                  .filter(x-&gt; x%2==0)\r\n                  .map(x-&gt;x*x)\r\n                  .forEach(System.out::println);\r\n    }\r\n}\r\n<\/pre>\n<p>In the above code we have <\/p>\n<ol>\n<li>Filter which takes Predicate as Param<\/li>\n<li>Map which takes Function as Param<\/li>\n<li>Sysout which takes Consumer as Param<\/li>\n<\/ol>\n<p>The filter, Consumer and sysout have been expanded from the above code as below. <\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class ReduceEgs {\r\n        public static void main(String&#x5B;] args) {\r\n            List&lt;Integer&gt; arrNumbers = Arrays.asList(1,2,4,5,7,6);\r\n    \r\n            arrNumbers.stream()\r\n                      .filter(getIntegerPredicate())\r\n                      .map(getFunction())\r\n                      .forEach(getPrintln());\r\n        }\r\n    \r\n        private static Consumer&lt;Integer&gt; getPrintln() {\r\n            return System.out::println;\r\n        }\r\n    \r\n        private static Function&lt;Integer, Integer&gt; getFunction() {\r\n            return x -&gt; x * x;\r\n        }\r\n    \r\n        private static Predicate&lt;Integer&gt; getIntegerPredicate() {\r\n            return x -&gt; x % 2 == 0;\r\n        }\r\n}\r\n<\/pre>\n<p>The Above code is refactored as below<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class ReduceEgs {\r\n        public static void main(String&#x5B;] args) {\r\n            List&lt;Integer&gt; arrNumbers = Arrays.asList(1,2,4,5,7,6);\r\n\r\n            Function&lt;Integer, Integer&gt; getSquare = x -&gt; x * x;\r\n            Predicate&lt;Integer&gt;         getEvenNo = x -&gt; x % 2 == 0;\r\n            Consumer&lt;Integer&gt;          showNos   = System.out::println;\r\n\r\n            arrNumbers.stream()\r\n                      .filter(getEvenNo)\r\n                      .map(getSquare)\r\n                      .forEach(showNos);\r\n        }\r\n}\r\n<\/pre>\n<p>What the java compiler does internally changes the above code as below. It created an anonymous inner class for implementing the methods in the interface.<\/p>\n<ol>\n<li><strong>Function <\/strong>has <strong>apply <\/strong>method which should be implemented<\/li>\n<li><strong>Consumer <\/strong>has <strong>accept <\/strong>method which should be implemented<\/li>\n<li><strong>Predicate <\/strong>has <strong>test <\/strong>method which should be implemented<\/li>\n<\/ol>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class ReduceEgs {\r\n        public static void main(String&#x5B;] args) {\r\n            List&lt;Integer&gt; arrNumbers = Arrays.asList(1,2,4,5,7,6);\r\n\r\n            Function&lt;Integer, Integer&gt; getSquare = new Function&lt;Integer, Integer&gt;() {\r\n                @Override\r\n                public Integer apply(Integer integer) {\r\n                    return integer * integer;\r\n                }\r\n            };\r\n\r\n            Predicate&lt;Integer&gt; getEvenNo =  new Predicate&lt;Integer&gt;() {\r\n                @Override\r\n                public boolean test(Integer integer) {\r\n                    return  integer % 2 == 0;\r\n                }\r\n            };\r\n\r\n            Consumer&lt;Integer&gt; showNos = new Consumer&lt;Integer&gt;() {\r\n                @Override\r\n                public void accept(Integer integer) {\r\n                    System.out.println(integer);\r\n                }\r\n            };\r\n\r\n            arrNumbers.stream()\r\n                      .filter(getEvenNo)\r\n                      .map(getSquare)\r\n                      .forEach(showNos);\r\n        }\r\n}\r\n<\/pre>\n<p>The output of all the above code is one and same as below<\/p>\n<pre>\r\n4\r\n16\r\n36\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>When to use Lambda Expressions If you have a functional Interface which has only one Abstract Method then we can use Lambda Expression at the Class which implements the functional interface and provides the method definition for the abstract method in Functional Interface. We have a Function Interface Printable with abstract method print Two classes&hellip; <a href=\"https:\/\/codethataint.com\/blog\/how-lambda-expression-works-internally\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[250],"tags":[],"class_list":["post-4280","post","type-post","status-publish","format-standard","hentry","category-lambdas"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/4280","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=4280"}],"version-history":[{"count":5,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/4280\/revisions"}],"predecessor-version":[{"id":4819,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/4280\/revisions\/4819"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=4280"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=4280"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=4280"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}