{"id":20,"date":"2025-02-10T07:37:51","date_gmt":"2025-02-10T07:37:51","guid":{"rendered":"https:\/\/mvmoure.com\/?p=20"},"modified":"2025-02-10T07:37:51","modified_gmt":"2025-02-10T07:37:51","slug":"lambda-expressions-in-java","status":"publish","type":"post","link":"https:\/\/mvmoure.com\/index.php\/2025\/02\/10\/lambda-expressions-in-java\/","title":{"rendered":"Lambda expressions in Java"},"content":{"rendered":"\n<p>This post is about using lambda expressions in Java. Lambda expressions are functions without a name that are commonly used in the functional programming style, specially to do iterations and filtering of lists.<\/p>\n\n\n\n<p>The way to define a lambda expression type is to define an interface with a single abstract (not defined) method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public interface Predicate&lt;T&gt; {\n    public boolean check(T object);\n}<\/code><\/pre>\n\n\n\n<p>Then another method could call a lambda expression defining the previous type, such as code like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public static filter(List&lt;T&gt; list, Predicate&lt;T&gt; fun) {\n    List&lt;T&gt; result = new ArrayList&lt;T&gt;();\n    for(T x : list) {\n        if(fun.check(x)) result.add(x);\n    }\n    return result;\n}<\/code><\/pre>\n\n\n\n<p>What&#8217;s now left is to define the code that will check our properties in the filter function and return the list containing those objects that match the predicate:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>List&lt;String&gt; data = List.of(\"hello\", \"world\", \"hi\");\nList&lt;String&gt; result = \n    filter(data, (s) -&gt; s&#91;0] == 'h'));<\/code><\/pre>\n\n\n\n<p>In this code sample, a lambda expression is used to return a boolean value corresponding to true if the string starts with the letter &#8220;h&#8221;. The value returned is a list with the elements that match the condition passed as a lambda expression.<\/p>\n\n\n\n<p>Lambda functions can be expressions (Java code that evaluates to a value) or if wrapped by curly braces ({}) a sequence of statements or instructions that optionally return a value.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Common functional interfaces<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Predicates<\/h4>\n\n\n\n<p>One commonly used functional interface is <code>Predicate&lt;T><\/code> which specifies in its interface a function <code>boolean test(T t)<\/code>. We could have defined in our previous example the argument to the function <code>filter<\/code> as a <code>Predicate<\/code> instead of creating our own interface.<\/p>\n\n\n\n<p>The function <code>filter<\/code> from the class <code>java.util.stream.Stream<\/code> takes one <code>Predicate<\/code> function as an argument, filtering out of the stream the elements that do not match the condition specified in it.<\/p>\n\n\n\n<p>Other functions in <code>Stream<\/code> that accept <code>Predicate<\/code> arguments are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>allMatch<\/code>, which takes a <code>Predicate<\/code> object and returns as a boolean whether all elements of a stream match the given predicate.<\/li>\n\n\n\n<li><code>anyMatch<\/code>, which is similar to <code>allMatch<\/code> but returns true if at least one element of the stream matches the predicate.<\/li>\n\n\n\n<li><code>noneMatch<\/code>, which returns true if no elements of the stream match the given predicate.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Functions<\/h4>\n\n\n\n<p>The functional interface <code>Function&lt;T,R><\/code> specifies the interface for a lambda function that takes one argument of type <code>T<\/code> and returns a value of type <code>R<\/code>.<\/p>\n\n\n\n<p>The usual <code>Stream<\/code> operator that accepts an object of type <code>Function<\/code> is the <code>map<\/code> operator, which applies the function to every element of the stream and gives as an output in the destination stream the return value of the <code>Function<\/code>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Consumers<\/h4>\n\n\n\n<p>The <code>Consumer&lt;T><\/code> functional interface defines a function that accepts one argument of type <code>T<\/code> and returns nothing, or <code>void<\/code>. This is used to process the stream with a function that normally has a side-effect, such as sending data to a database or a file, and wants not to pass any result to the stream, but instead &#8220;consumes&#8221; it or takes it out of the stream.<\/p>\n\n\n\n<p>A <code>Stream<\/code> function that would use a <code>Consumer<\/code> interface is the method <code>forEach<\/code>, which just calls the function for each element, consuming all elements of the stream. Another <code>Stream<\/code> function taking a <code>Consumer<\/code> argument would be <code>peek<\/code>, which returns the stream intact to allow other operations, but executes the input function every time that an element of the stream is consumed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Manipulating collections with lambda functions and streams<\/h3>\n\n\n\n<p>The main class that implements functional methods such as <code>map<\/code>, <code>filter<\/code>, et c. is the class <code>Stream<\/code>. One can use <code>Stream<\/code> directly or instead convert one of the many  types that extend or implement <code>java.util.Collection<\/code>, such as <code>LinkedList<\/code>, to a <code>Stream<\/code> object.<\/p>\n\n\n\n<p>To do that, one would call the function <code>stream()<\/code> of any list or object that subclassed the class <code>java.util.Collection<\/code>. If needed, the final result of the operations could be converted back to a <code>List<\/code> object by calling <code>Stream<\/code>&#8216;s function <code>toList()<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">References<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/docs.oracle.com\/javase\/tutorial\/java\/javaOO\/lambdaexpressions.html\" data-type=\"link\" data-id=\"https:\/\/docs.oracle.com\/javase\/tutorial\/java\/javaOO\/lambdaexpressions.html\">Lambda Expressions<\/a>, Java Reference.<\/li>\n\n\n\n<li><a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.base\/java\/util\/function\/package-summary.html\" data-type=\"link\" data-id=\"https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.base\/java\/util\/function\/package-summary.html\">java.util.function package<\/a>, Java 21 Reference.<\/li>\n\n\n\n<li><a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.base\/java\/util\/Collection.html\" data-type=\"link\" data-id=\"https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.base\/java\/util\/Collection.html\">java.util.Collection<\/a>, Java 21 Reference.<\/li>\n\n\n\n<li><a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.base\/java\/util\/List.html\" data-type=\"link\" data-id=\"https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.base\/java\/util\/List.html\">java.util.List class<\/a>, Java 21 Reference.<\/li>\n\n\n\n<li><a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.base\/java\/util\/stream\/Stream.html\" data-type=\"link\" data-id=\"https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.base\/java\/util\/stream\/Stream.html\">java.util.stream.Stream class<\/a>, Java 21 Reference.<\/li>\n<\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This post is about using lambda expressions in Java. Lambda expressions are functions without a name that are commonly used in the functional programming style, specially to do iterations and filtering of lists. The way to define a lambda expression type is to define an interface with a single abstract (not defined) method: Then another [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[6,5,4],"class_list":["post-20","post","type-post","status-publish","format-standard","hentry","category-programming","tag-functional-programming","tag-java","tag-programming"],"_links":{"self":[{"href":"https:\/\/mvmoure.com\/index.php\/wp-json\/wp\/v2\/posts\/20","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mvmoure.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mvmoure.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mvmoure.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mvmoure.com\/index.php\/wp-json\/wp\/v2\/comments?post=20"}],"version-history":[{"count":6,"href":"https:\/\/mvmoure.com\/index.php\/wp-json\/wp\/v2\/posts\/20\/revisions"}],"predecessor-version":[{"id":63,"href":"https:\/\/mvmoure.com\/index.php\/wp-json\/wp\/v2\/posts\/20\/revisions\/63"}],"wp:attachment":[{"href":"https:\/\/mvmoure.com\/index.php\/wp-json\/wp\/v2\/media?parent=20"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mvmoure.com\/index.php\/wp-json\/wp\/v2\/categories?post=20"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mvmoure.com\/index.php\/wp-json\/wp\/v2\/tags?post=20"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}