{"id":2905,"date":"2023-07-07T16:00:21","date_gmt":"2023-07-07T16:00:21","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=2905"},"modified":"2025-10-04T09:19:00","modified_gmt":"2025-10-04T09:19:00","slug":"java-lambda","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-lambda\/","title":{"rendered":"Java Lambda Expressions: What are they and how do they work?"},"content":{"rendered":"<p>Many <a href=\"https:\/\/msg-life.sk\/en\/jobs\/java-programmer-senior\/\">Java developers<\/a> have already encountered lambda expressions. This functionality was added in the 2014 version of Java 8, so it is no longer a new feature. It is often used by developers and has many advantages. However, if you find lambda expressions difficult or don&#8217;t know what they represent, you&#8217;ve come to the right place.  <\/p>\n<h2>Lambda expression meaning<\/h2>\n<p>The lambda expression represents functionality that was added in Java 8. It is a short block of code similar to a method, but unlike it, it does not need the method&#8217;s name and can be implemented directly in the body of the method. <\/p>\n<p>Lambda has several advantages:<\/p>\n<ul>\n<li><strong>it clarifies the code and provides better readability<\/strong> &#8211; instead of several lines of code, you only need to write a few lines,<\/li>\n<li><strong>it allows you to use functional programming<\/strong> &#8211; that is, to use a function as an input parameter of another function,<\/li>\n<li><strong>it improves code parallelization<\/strong> &#8211; in other words, more efficient code execution on multicore processes.<\/li>\n<\/ul>\n<h2>Lambda expression syntax<\/h2>\n<p>Each lambda expression must have the <strong>correct syntax.<\/strong> Only then will it have the desired effect. Lambda must contain:<\/p>\n<ul>\n<li>list of arguments,<\/li>\n<li>the arrow sign,<\/li>\n<li>the body of the expression.<\/li>\n<\/ul>\n<p>In practice, it may look like this:<\/p>\n<p><strong>(argument list) -&gt; expression body<\/strong><\/p>\n<p><strong>(argument list) -&gt; {expression1; expression2, &#8230;}<\/strong><\/p>\n<p><strong> <\/strong>The argument list can also be <strong>empty<\/strong>, for example:<\/p>\n<p><strong>() -&gt; { System.out.println(\u201eAhoj\u201c); }<\/strong><\/p>\n<p><strong> <\/strong>The body of the expression must only contain compound parentheses if it contains <strong>more than one line of code<\/strong>. In the above example, we can omit them:<\/p>\n<p><strong>() -&gt; System.out.println(\u201eAhoj\u201c);<\/strong><\/p>\n<p><strong> <\/strong>The argument types may or may not be defined, which means that the two expressions are <strong>equivalent<\/strong>:<\/p>\n<p><strong>(x) -&gt; System.out.println(x);<\/strong><\/p>\n<p><strong>(Int x) -&gt; System.out.println(x);<\/strong><\/p>\n<p><strong> <\/strong>Lambda can also <strong> return values<\/strong> without using the <em>return<\/em> word. The compiler can infer this itself:<\/p>\n<p><strong>(x, y) -&gt; x + y<\/strong><\/p>\n<div class=\"inside\"><\/div>\n<h2>Java lambda expressions example<\/h2>\n<p>To give you a better idea, here are <strong>three examples<\/strong> of how a lambda expression can be used.<\/p>\n<h3>Example No. 1: Lambda expression in forEach<\/h3>\n<p>Lambda expressions are often used as <strong>function parameters<\/strong>.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">package com.test;\n\nimport java.util.ArrayList;\n\npublic class LambdaExample1 {\n\n\tpublic static void main(String[] args) {\n\t\tArrayList&lt;Integer&gt; numbers = new ArrayList&lt;Integer&gt;();\n\t\tnumbers.add(1);\n\t\tnumbers.add(2);\n\t\tnumbers.add(3);\n\t\t\/\/ Vytlaci na konzolu 1 2 3 pod sebou. \n\t\tnumbers.forEach(x -&gt; System.out.println(x));\n\t}\n}<\/code><\/pre>\n<p>The lambda expression can be saved in a <strong>variable<\/strong>. However, this only applies if the variable interfaces with a single method. In such cases, the lambda expression must have the same number of parameters and return type as the method.<\/p>\n<p>Java has <strong>many user interfaces.<\/strong> One example is the consumer interface used with lists:<\/p>\n<pre><code class=\"language-java\" data-line=\"\">java.util.function.Consumer&lt;Integer&gt; function = x -&gt; System.out.println(x);\nnumbers.forEach(function);<\/code><\/pre>\n<h3>Example No. 2: Defining a functional interface for a lambda expression<\/h3>\n<p>The second example shows how to create a functional interface for <strong>basic mathematical operations<\/strong>. You can insert expressions for addition, subtraction, multiplication, division and the <em>operate<\/em> method. Their job is to take two numbers and the associated lambda expression calculates the result, which looks like this:<\/p>\n<pre><code class=\"language-java\" data-line=\"\">4 + 2 = 6 \n4 - 2 = 2\n4 * 2 = 8\n4 \/ 2 = 2<\/code><\/pre>\n<p>Thanks to the operate method, the associated lambda expression calculates the result quickly and easily.<\/p>\n<p>You can use lambda expressions in the functional interface for basic mathematical operations.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">package com.test;\n\nimport java.lang. ArithmeticException;\n\npublic class LambdaExample2 {\n    \/\/ Deklarovanie interfejsu pre lamda vyraz\n    interface MathOperation {\n        int operation(int x, int y);\n    }\n    \/\/ Deklarovanie metody pre matematicku operaciu\n    private int operate (int x, int y, MathOperation mathOperation) {\n        return mathOperation.operation (x, y);\n    }\n    \/\/ Vypis celej operacie do konzoly.\n    public static void printResult(int x, char c, int y, int z) {\n        System.out.printf(&quot;%d %s %d = %d\\n&quot;, x, c, y, z);\n    }\n    public static void main(String[] args) {\n        \/\/ Bez deklaracie typu\n        MathOperation addition = (x, y) -&gt; x + y;\n        \/\/ S deklaraciou typu (int)\n        MathOperation substraction = (int x, int y) -&gt; x - y;\n        \/\/ S klucovym slovom return (musi byt v krutenych zatvorkach)\n        MathOperation multiplication = (x, y) -&gt; { return (x * y); };\n        \/\/ Viacriadkovy lambda vyraz\n        MathOperation division = (x, y) -&gt; {\n            if(y != 0)\n                return (x \/ y);\n            else\n                throw new ArithmeticException(&quot;You shouldn&#039;t divide a number by zero!&quot;);\n        };\n\n        LambdaExample2 test = new LambdaExample2();\n        int a = 4; int b = 2;\n        \/\/ Scitanie dvoch cisiel\n        printResult(a, &#039;+&#039;, b, test.operate (a, b, addition));\n        \/\/ Odcitanie dvoch cisiel\n        printResult(a, &#039;-&#039;, b, test.operate (a, b, substraction));\n        \/\/ Vynasobenie dvoch cisiel\n        printResult(a, &#039;*&#039;, b, test.operate (a, b, multiplication));\n        \/\/ Vydelenie dvoch cisiel\n        printResult(a, &#039;\/&#039;, b, test.operate (a, b, division));\n    }\n}<\/code><\/pre>\n<h3>Example No. 3: Sorting, filtering and iterating collections using lambda expressions<\/h3>\n<p>The advantage of lambda expressions is that they reduce the need to write custom helper methods. At the same time, they also <strong>shorten and clarify the code<\/strong>, making the whole job easier. The power of lambdas is particularly evident when combined with other Java functionality, such as collections.<\/p>\n<p>The following example shows how lambda expressions can be used to easily <strong>sort, filter and iterate<\/strong> objects in a collection:<\/p>\n<pre><code class=\"language-java\" data-line=\"\">package com.test;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.stream.Stream;\n\nclass Product {\n    String name;\n    double price;\n\n    public Product(String name, double price) {\n        this.name = name;\n        this.price = price;\n    }\n}\n\npublic class LambdaExample3 {\n\n    public static Product createProduct(String name, double price) {\n        return new Product(name, price);\n    }\n\n    public static void main(String[] args) {\n        List&lt;Product&gt; products = new ArrayList();\n        products.add(createProduct(&quot;Chlieb&quot;, 1.0));\n        products.add(createProduct(&quot;Mlieko&quot;, 0.5));\n        products.add(createProduct(&quot;Keksy&quot;, 0.8));\n        products.add(createProduct(&quot;Smotana&quot;, 0.4));\n        products.add(createProduct (&quot;Cokolada&quot;, 0.7));\n\n        \/\/ Sortovanie nazvov produktov podla abecedy cez lambdu\n        products.sort((p1, p2) -&gt; p1.name.compareTo(p2.name));\n\n        \/\/ Vyfiltrovanie produktov s cenou (0.5. 1.0)\n        Stream&lt;Product&gt; filteredProducts = products.stream().filter(p -&gt; p.price &gt; 0.5 &amp;&amp; p.price &lt; 1.0);\n\n        \/\/ Iterovanie v kolekcii\n        filteredProducts.forEach(product -&gt; System.out.println(product.name + &quot;: &quot; + product.price));\n    }\n}<\/code><\/pre>\n<p>The output looks like this:<\/p>\n<pre><code class=\"language-java\" data-line=\"\">Cokolada: 0.7\nKeksy: 0.8<\/code><\/pre>\n<h2>Lambda expressions make your work easier and faster<\/h2>\n<p>Lambda expressions are a great feature of the Java programming language. Using them can <strong>make your work easier and faster<\/strong>. They also make code cleaner and open up new possibilities. Lambda is part of Java since <a href=\"https:\/\/msgprogramator.sk\/en\/java-jdk\/\">Java 8<\/a>. So if you&#8217;re running an older version, it&#8217;s worth thinking about upgrading.<\/p>\n<p>We have prepared files with the above Java Lambda examples that you can run directly in Java. <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/08\/Lambda.zip\">Download the code here.<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Do you have problems with lambda expressions or do you not know what they mean? You&#8217;re in the right place.<\/p>\n","protected":false},"author":14,"featured_media":1824,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-2905","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2905","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/comments?post=2905"}],"version-history":[{"count":7,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2905\/revisions"}],"predecessor-version":[{"id":9202,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2905\/revisions\/9202"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/1824"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=2905"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=2905"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=2905"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}