{"id":5265,"date":"2021-03-23T16:22:50","date_gmt":"2021-03-23T16:22:50","guid":{"rendered":"https:\/\/ded9.com\/?p=5265"},"modified":"2026-02-16T09:00:09","modified_gmt":"2026-02-16T09:00:09","slug":"learn-lambda-expressions-in-java-lambda-expressions","status":"publish","type":"post","link":"https:\/\/ded9.com\/tr\/learn-lambda-expressions-in-java-lambda-expressions\/","title":{"rendered":"Mastering Lambda Expressions in Java: A Clear, Practical Guide"},"content":{"rendered":"<p><span style=\"font-size: 12pt;\">When Java 8 was released, lambda expressions were a hot topic. <a href=\"https:\/\/www.w3schools.com\/java\/java_lambda.asp\" target=\"_blank\" rel=\"noopener\">Lambda expressions<\/a> have been added to JDK version 8 to enhance Java performance by increasing the language&#8217;s expressive power.<\/span><\/p>\n<p>But before entering Lambda, we must first know the user interface.<\/p>\n<h2><span style=\"font-size: 18pt;\">What is a user interface?<\/span><\/h2>\n<p>If a Java interface contains only one abstract method, it is called a functional interface. For example, the Runnable interface of the package, Java.lang, is functional because it forms only one method, run ().<\/p>\n<p><strong>Example 1: Define a user interface or interface in Java<\/strong><\/p>\n<blockquote>\n<ol>\n<li dir=\"ltr\">import java.lang.FunctionalInterface;<\/li>\n<li dir=\"ltr\">@FunctionalInterface<\/li>\n<li dir=\"ltr\">public interface MyInterface {<\/li>\n<li dir=\"ltr\">double getValue ();<\/li>\n<li dir=\"ltr\">}<\/li>\n<\/ol>\n<\/blockquote>\n<p><strong>Note:<\/strong>\u00a0Annotating @ FunctionalInterface is not necessary, but it is wise to use it because the Java compiler forces the defined interface to be a functional interface and should only have an abstract method.\u00a0In Java 7, the interface was called the Abstract Method Single or SAM type.<\/p>\n<p>SAM was usually run with anonymous classes in Java 7.<\/p>\n<p><strong>Example 2: Run SAM with anonymous classes in Java<\/strong><\/p>\n<blockquote>\n<ol>\n<li dir=\"ltr\">public class FunctionInterfaceTest {<\/li>\n<li dir=\"ltr\">public static void main (String [] args) {<\/li>\n<li dir=\"ltr\">new Thread (new Runnable () {<\/li>\n<li dir=\"ltr\">@Override<\/li>\n<li dir=\"ltr\">public void run () {<\/li>\n<li dir=\"ltr\">System.out.println (&#8220;I just implemented the Runnable Functional Interface.&#8221;);<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">}). start ();<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">}<\/li>\n<\/ol>\n<\/blockquote>\n<p>The ability to send an anonymous class to the constructor or method made writing Java 7 code with fewer files easy. However, the structure was still tricky, and a lot of code was needed.<\/p>\n<p>Java 8 went one step further, increasing the power of a SAM.\u00a0Since we know that an interface has only one method, there is no need to define the name of that method when sending it as an argument.\u00a0The term lambda allows us to do just that.<\/p>\n<h2>Familiarity with the term lambda<\/h2>\n<p>Lambda is essentially an unknown or unspecified method that is not executed alone. Instead, it implements the method defined by the interface.<\/p>\n<h2><strong>How do you define the term lambda in Java?<\/strong><\/h2>\n<p>The term lambda introduces a new syntactic element and operator in Java.\u00a0The new operator is called the lambda operator or the arrow operator.\u00a0(-&gt;)<\/p>\n<p>Let&#8217;s write a simple method that returns only a constant double value.<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">double getPiValue () {return 3.1415; }<\/pre>\n<\/div>\n<h3>The lambda expression equivalent to the above method is:<\/h3>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">() -&gt; 3.1415<\/pre>\n<\/div>\n<p>In the lambda expression, the left side specifies the required parameters of the expression, while the right is the lambda body, which determines the function of the lambda expression.<\/p>\n<p>The Lambda body is of two types.<\/p>\n<p>1- Body with a single phrase<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">() -&gt; System.out.println (\u201cLambdas are great\u201d);<\/pre>\n<\/div>\n<p>2- The body consists of a block of code<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">() -&gt; {\r\n\r\ndouble pi = 3.1415;\r\n\r\nreturn pi;\r\n\r\n}<\/pre>\n<\/div>\n<h3><span style=\"font-size: 14pt;\">A lambda expression can have a parameter. For example:<\/span><\/h3>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">(n) -&gt; (n% 2) == 0<\/pre>\n<\/div>\n<p>This lambda expression specifies that the value of n is even or odd.<\/p>\n<p>If the body of the Lambda is a block of code, you should always return a value. However, a return value is not required if the lambda body is just a phrase.<\/p>\n<p>Let&#8217;s write the Java <a href=\"https:\/\/ded9.com\/how-to-code-with-python-and-benefit-from-it\/\">code <\/a>with the lambda expression that returns the value of <a href=\"https:\/\/en.wikipedia.org\/wiki\/Pi\" target=\"_blank\" rel=\"noopener\">Pi<\/a>.<\/p>\n<p>As mentioned earlier, the term lambda is not used alone. Executing the abstract method defined by the interface constitutes a function.<\/p>\n<p><strong>Example 3: Define the term Lambda with the user interface (interface) in Java<\/strong><\/p>\n<p>We must first define a MyInterface.java user interface:<\/p>\n<blockquote>\n<ol>\n<li dir=\"ltr\">import java.lang.FunctionalInterface;<\/li>\n<li dir=\"ltr\">\/\/ This is functional interface<\/li>\n<li dir=\"ltr\">@FunctionalInterface<\/li>\n<li dir=\"ltr\">public interface MyInterface {<\/li>\n<li dir=\"ltr\">double getPiValue ();<\/li>\n<li dir=\"ltr\">}<\/li>\n<\/ol>\n<\/blockquote>\n<p>Now, let&#8217;s take the lambda expression as an example of a functional interface.<\/p>\n<blockquote>\n<ol>\n<li dir=\"ltr\">public class LambdaMain {<\/li>\n<li dir=\"ltr\">public static void main (String [] args) {<\/li>\n<li dir=\"ltr\">MyInterface myInterface;<\/li>\n<li dir=\"ltr\">myInterface = () -&gt; 3.1415;<\/li>\n<li dir=\"ltr\"><\/li>\n<li dir=\"ltr\">System.out.println (\u201cValue of Pi =\u201d + myInterface.getPiValue ());<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">}<\/li>\n<\/ol>\n<\/blockquote>\n<h4>The output is equal to:<\/h4>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">Value of Pi = 3.1415<\/pre>\n<\/div>\n<p>The lambda expression must be consistent with the abstract method. That is, if you assign () -&gt; &#8220;3.1415&#8221; to the myInterface instance, the code is defective and will not run because, by definition in the interface, the string type is not compatible with double.<\/p>\n<p>You probably do not use a lambda phrase like the above in a real application. Let&#8217;s look at another example of a lambda expression that takes parameters.<\/p>\n<p><strong>Example 4: Using the term lambda with parameters in Java<\/strong><\/p>\n<p><strong><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-257980 size-full\" src=\"https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/collect04d.png\" alt=\"Example 4: Using the term lambda with parameters in Java\" width=\"734\" height=\"210\" srcset=\"https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/collect04d.png 734w, https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/collect04d-300x86.png 300w\" sizes=\"(max-width: 734px) 100vw, 734px\" \/><\/strong><\/p>\n<blockquote>\n<ol>\n<li dir=\"ltr\">@FunctionalInterface<\/li>\n<li dir=\"ltr\">MyInterface {interface<\/li>\n<li dir=\"ltr\">Reverse string (String n);<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">public class ParamLambdaMain {<\/li>\n<li dir=\"ltr\">public static void main (String [] args) {<\/li>\n<li dir=\"ltr\">MyInterface myInterface = (str) -&gt;<\/li>\n<li dir=\"ltr\">String result = \u201c\u201d;<\/li>\n<li dir=\"ltr\">for (int i = str.length () &#8211; 1; i&gt; = 0; i\u2013)<\/li>\n<li dir=\"ltr\">result + = str.charAt (i);<\/li>\n<li dir=\"ltr\">return result;<\/li>\n<li dir=\"ltr\">};<\/li>\n<li dir=\"ltr\">System.out.println (\u201cLambda reversed =\u201d + myInterface.reverse (\u201cLambda\u201d));<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">}<\/li>\n<\/ol>\n<\/blockquote>\n<p>Output<\/p>\n<blockquote>\n<p dir=\"ltr\">Lambda reversed = adbmaL<\/p>\n<\/blockquote>\n<h2>General functional interface<\/h2>\n<p>The above interface only accepts String and returns the StrStringject. However, we can create a public user interface that accepts any data type.<\/p>\n<p><strong>Example 5: How can a user interface accept any data type in Java?<\/strong><\/p>\n<p>Let&#8217;s see how this is done:<\/p>\n<blockquote>\n<ol>\n<li dir=\"ltr\">\/\/ GenericInterface.java<\/li>\n<li dir=\"ltr\">@FunctionalInterface<\/li>\n<li dir=\"ltr\">interface GenericInterface &lt;T&gt; {<\/li>\n<li dir=\"ltr\">T func (T t);<\/li>\n<li dir=\"ltr\">}<\/li>\n<\/ol>\n<\/blockquote>\n<h4>Now, the Generic Interface is compatible with any Lambda expression that takes a parameter and returns a value of the same type.<\/h4>\n<blockquote>\n<ol>\n<li dir=\"ltr\">\/\/ GenericLambda.java<\/li>\n<li dir=\"ltr\">public class GenericLambda {<\/li>\n<li dir=\"ltr\">public static void main (String [] args) {<\/li>\n<li dir=\"ltr\">GenericInterface &lt;String&gt; reverse = (str) -&gt; {<\/li>\n<li dir=\"ltr\">String result = \u201c\u201d;<\/li>\n<li dir=\"ltr\">for (int i = str.length () &#8211; 1; i&gt; = 0; i\u2013)<\/li>\n<li dir=\"ltr\">result + = str.charAt (i);<\/li>\n<li dir=\"ltr\">return result;<\/li>\n<li dir=\"ltr\">};<\/li>\n<li dir=\"ltr\">System.out.println (&#8220;Lambda reversed =&#8221; + reverse.func (&#8220;Lambda&#8221;));<\/li>\n<li dir=\"ltr\">GenericInterface &lt;Integer&gt; factorial = (n) -&gt; {<\/li>\n<li dir=\"ltr\">int result = 1;<\/li>\n<li dir=\"ltr\">for (int i = 1; i &lt;= n; i ++)<\/li>\n<li dir=\"ltr\">result = i * result;<\/li>\n<li dir=\"ltr\">return result;<\/li>\n<li dir=\"ltr\">};<\/li>\n<li dir=\"ltr\">System.out.println (\u201cfactorial of 5 =\u201d + factorial.func (5));<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">}<\/li>\n<\/ol>\n<\/blockquote>\n<p>Output<\/p>\n<blockquote>\n<p dir=\"ltr\">Lambda reversed = adbmaL<\/p>\n<p dir=\"ltr\">factorial of 5 = 120<\/p>\n<\/blockquote>\n<h2 style=\"text-align: left;\">Lambda Expressions and API flow<\/h2>\n<h2 style=\"text-align: center;\"><img decoding=\"async\" class=\"alignnone wp-image-257977 size-full\" src=\"https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/lambdaexpsyntax.png\" alt=\"Lambda Expressions and API flow\" width=\"295\" height=\"205\" \/><\/h2>\n<p>A new Java. Util. The stream package has been added to JDK8, which allows Java programmers to perform operations such as search, filter, map, reduce, or otherwise manipulate collections such as lists.<\/p>\n<p>For example, we have a data stream (a string list) in which each String combines the country&#8217;s String and the country&#8217;s location. Now, we can process this data stream and retrieve only the Nepal locations.<\/p>\n<p><strong>Example 6: Demonstrate the use of Lambda with the API stream<\/strong><\/p>\n<blockquote>\n<ol>\n<li dir=\"ltr\">import java.util.ArrayList;<\/li>\n<li dir=\"ltr\">import java.util.List;<\/li>\n<li dir=\"ltr\">public class StreamMain {<\/li>\n<li dir=\"ltr\">static List &lt;String&gt; places = new ArrayList &lt;&gt; ();<\/li>\n<li dir=\"ltr\">\/\/ preparing our data<\/li>\n<li dir=\"ltr\">public static List getPlaces () {<\/li>\n<li dir=\"ltr\">places.add (\u201cNepal, Kathmandu\u201d);<\/li>\n<li dir=\"ltr\">places.add (\u201cNepal, Pokhara\u201d);<\/li>\n<li dir=\"ltr\">places.add (\u201cIndia, Delhi\u201d);<\/li>\n<li dir=\"ltr\">places.add (&#8220;USA, New York&#8221;);<\/li>\n<li dir=\"ltr\">places.add (\u201cAfrica, Nigeria\u201d);<\/li>\n<li dir=\"ltr\">return places;<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">public static void main (String [] args) {<\/li>\n<li dir=\"ltr\">List &lt;String&gt; myPlaces = getPlaces ();<\/li>\n<li dir=\"ltr\">System.out.println (\u201cPlaces from Nepal:\u201d);<\/li>\n<li dir=\"ltr\"><\/li>\n<li dir=\"ltr\">\/\/ Filter places from Nepal<\/li>\n<li dir=\"ltr\">myPlaces.stream ()<\/li>\n<li dir=\"ltr\">.filter ((p) -&gt; p.startsWith (\u201cNepal\u201d))<\/li>\n<li dir=\"ltr\">.map ((p) -&gt; p.toUpperCase ())<\/li>\n<li dir=\"ltr\">.sorted ()<\/li>\n<li dir=\"ltr\">.forEach ((p) -&gt; System.out.println (p));<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">}<\/li>\n<\/ol>\n<\/blockquote>\n<h4>Output<\/h4>\n<blockquote>\n<p dir=\"ltr\">Places from Nepal:<\/p>\n<p dir=\"ltr\">NEPAL, KATHMANDU<\/p>\n<p dir=\"ltr\">NEPAL, POKHARA<\/p>\n<\/blockquote>\n<p>The API stream allows us to access methods such as filter (), map, and forEach () that can take a lambda expression as input.<\/p>\n<p>We can use both built-in Java methods and define our expressions based on the technique we learned above. As we saw in the example above, this dramatically reduces the lines of code.<\/p>\n<h2>FAQ<\/h2>\n<div id=\"rank-math-rich-snippet-wrapper\"><div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-1\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What is a lambda expression in Java and why was it added?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>A lambda expression is essentially an anonymous method \u2014 a short block of code that you can pass around like an object, to implement a single-method (functional) interface. It was introduced in Java 8 to reduce boilerplate code, especially where anonymous classes were previously used.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-2\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What is the basic syntax of a lambda expression?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>The basic form is: (parameters) -&gt; { body } For example: (a, b) -&gt; a + b If there\u2019s only one parameter and the type can be inferred, parentheses can be omitted: x -&gt; x * x<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-3\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">When and how should I use lambda expressions effectively?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Use lambdas when you need to implement a functional interface (an interface with exactly one abstract method). Common applications include passing behavior as an argument (for example, to forEach, filter, map on collections), sorting with comparators, or event handling. It\u2019s best to use standard functional interfaces from java.util.function (like Predicate, Consumer, Function) instead of creating custom ones unless necessary.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>When Java 8 was released, lambda expressions were a hot topic. Lambda expressions have been added to JDK version 8 to enhance Java performance by increasing the language&#8217;s expressive power. But before entering Lambda, we must first know the user interface. What is a user interface? If a Java interface contains only one abstract method, [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":5266,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[11513],"tags":[840,11982],"class_list":["post-5265","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java-2","tag-java","tag-pi"],"acf":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/posts\/5265","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/comments?post=5265"}],"version-history":[{"count":5,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/posts\/5265\/revisions"}],"predecessor-version":[{"id":267011,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/posts\/5265\/revisions\/267011"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/media\/5266"}],"wp:attachment":[{"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/media?parent=5265"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/categories?post=5265"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/tags?post=5265"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}