<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tushar Jajodia on Medium]]></title>
        <description><![CDATA[Stories by Tushar Jajodia on Medium]]></description>
        <link>https://medium.com/@jajodiatushar?source=rss-670af1b7a18f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*e8_1hunadHg9hnqEKry0IQ.jpeg</url>
            <title>Stories by Tushar Jajodia on Medium</title>
            <link>https://medium.com/@jajodiatushar?source=rss-670af1b7a18f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:11:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jajodiatushar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Completable Future In a Java]]></title>
            <link>https://medium.com/@jajodiatushar/completable-future-in-a-java-d522acd89799?source=rss-670af1b7a18f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d522acd89799</guid>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[callable]]></category>
            <category><![CDATA[thenapply]]></category>
            <category><![CDATA[completablefuture]]></category>
            <dc:creator><![CDATA[Tushar Jajodia]]></dc:creator>
            <pubDate>Sun, 29 Mar 2020 19:18:54 GMT</pubDate>
            <atom:updated>2020-03-29T19:18:54.219Z</atom:updated>
            <content:encoded><![CDATA[<p>After searching a lot about Completable Future and not finding any complete article I decided to write one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jlBv75VcdezKL4K3UTw72A.jpeg" /></figure><p>Before proceeding further, I assume that you know about</p><ul><li>Multi-Threading in Java</li><li><a href="https://medium.com/@jajodiatushar/lambdas-and-functional-programming-in-java-39dc8275f183">Functional Programming in Java.</a></li></ul><p>The basic problem with the multi threading in Java is this particular method definition of the Runnable Interface.</p><pre>public void run(){}</pre><p>Which has to be overridden if you want to execute some piece of code in the new thread. <br>The problem is that you can only execute some code but you cannot return something from the thread to the caller of the Thread, after the execution has been completed and there is no support for Exception as well meaning you will have to handle it in the run method itself.</p><p>To Solve this problem Java came up with Something called as <strong>Callable</strong>. Which has a method that can return anything, and throws the Exception.<br>You have to override this method just like run method of Runnable Interface.</p><pre>public interface Callable&lt;V&gt; {<em><br>    </em>V call() throws Exception;<br>}</pre><p>But you can only create <strong>Thread </strong>with <strong>Runnable </strong>not <strong>Callable</strong>.<br>For <strong>Callable </strong>run like <strong>Runnable </strong>you have to submit the <strong>Callable </strong>to <strong>ExecutorService</strong>.</p><pre>ExecutorService service = Executors.<em>newSingleThreadExecutor</em>();<br>Future&lt;&gt; submit = executorService.submit(callable);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*lGhnA0u12bZh_2WyPlHg9g.png" /></figure><p>As <strong>Callable</strong> return result, there has to be something that holds the result. So Java Introduced <strong>Future</strong>.<br>Which doesn’t contain the result <strong>immediately</strong>, but will contain the result once the thread <strong>completes</strong> the operation. <br>You can get the result by calling the <strong>get </strong>method of the future object.<br>(<em>It is a blocking operation)</em></p><h4>Problems with Future</h4><ul><li>You cannot perform further operation on the result without <strong>blocking</strong> it.</li><li>You cannot chain multiple <strong>Future </strong>together.</li><li>You cannot combine multiple <strong>Future</strong> together.</li><li>No support for Exception Handling.</li></ul><p>There are a lot of limitations with <strong>Future</strong>. <br>The only way to the obtain the result from the <strong>Future </strong>is to use the <strong>get()</strong> method, (<em>which is blocking operation)</em>. <br>Suppose you have two task that needs to be executed one after the other. <br>The Execution of the second task also depends upon the first task’s result.</p><pre>ExecutorService executorService = Executors.<em>newFixedThreadPool</em>(2);<br>Future&lt;String&gt; firstFuture = executorService.submit(firstCallable);</pre><pre><strong>String firstData = firstFuture.get();</strong></pre><pre>if(firstData){ //somecondition<br>           Future&lt;String&gt; secondFuture = <br>executorService.submit(secondFuture);<br>}</pre><p>Here the third line blocks the main thread’s execution.<br>Moreover you cannot chain the further operations.</p><h3>Completable Future.</h3><pre>public class <strong>CompletableFuture&lt;T&gt; </strong>extends Object<br>implements Future&lt;T&gt;, CompletionStage&lt;T&gt;</pre><p>You will generally run two types of task in CompletableFuture. One that returns something and the other don’t.</p><pre>CompletableFuture.runAsync(Runnable);<br>CompletableFuture.supplyAsync(Supplier);</pre><p>The First one takes our old <strong>Runnable Interface’s</strong> instance and the other one takes the instance of <strong>Supplier Interface</strong>. (Supplier are Functional Interfaces)</p><pre>CompletableFuture cf1 = CompletableFuture.<em>runAsync</em>(()-&gt; System.<em>out</em>.println(&quot;Hello World&quot;));</pre><pre>CompletableFuture cf2 = <br>CompletableFuture.<em>supplyAsync</em>(()-&gt;&quot;Hello World&quot;);</pre><p>Using Lambda’s makes it more simple. Moreover you don’t need to handle the <strong>Executors </strong>if you don’t want to. The best part of the CompletableFuture is however not this. <br>What makes the CF so powerful is that you can chain them, handle exception and do a lot more without blocking the main Thread.</p><h4>Chaining</h4><ul><li><strong>thenApply </strong><br>If you want to do some more operation after you get the result from the Thread. You can use thenApply. It takes the Function type of Functional Interface.</li></ul><p>The Definition of the method thenApply</p><pre>CompletableFuture&lt;U&gt; thenApply(Function&lt;T,U&gt; fn)</pre><p>here, Function&lt;T,U&gt; means “T” is the input argument and “U” is the output.<br>Here “T” is what our CF will return and “U” will be what we want to return.</p><pre>CompletableFuture&lt;Integer&gt; cf = CompletableFuture.supplyAsync<br>(()-&gt;&quot;5&quot;).thenApply(result -&gt; Integer.parseInt(result));</pre><p>Here as our CF returns <strong>String </strong>so “T” in Function&lt;T,U&gt; becomes <strong>String </strong>and we are return <strong>Integer </strong>from <strong>thenApply</strong> method so “U” becomes <strong>Integer</strong>.<br>See our Completable Future also gets transferred from <br><strong>CompletableFuture&lt;String&gt; to CompletableFuture&lt;Integer&gt;</strong><br>Here the same thread does the additional work.<br><strong>No new thread is Created.</strong></p><p>If We were to do the same thing using Future we would have to do something like</p><pre>ExecutorService executorService = Executors.<em>newFixedThreadPool</em>(1);<br>Future&lt;String&gt; future = executorService.submit(() -&gt; &quot;5&quot;);<br>String str = future.get();  // Blocking Operation<br>int data = Integer.<em>parseInt</em>(str);</pre><blockquote>However in the previous example we got the CompletableFuture&lt;Integer&gt; not the Integer as in the second example.<br> Again if want to get the data from the CompletableFuture we will need to use get() which is again blocking so what is the benefit of using CompletableFuture<br>I will answer this shortly.</blockquote><ul><li><strong>thenAccept</strong></li></ul><p><strong>thenApply </strong>and <strong>thenAccept </strong>are quite similar except that “thenApply” takes Function Type as argument and “thenAccept” takes Consumer Type as argument.<br><em>You would already know “Consumers” don’t return anything like Function.</em></p><pre>CompletableFuture&lt;Void&gt; thenAccept(Consumer&lt;T&gt; action) </pre><p>So if you want to consume the result of the CompletableFuture and don’t want to apply any future operation in the result after this operation.</p><pre>CompletableFuture&lt;Void&gt; cf = CompletableFuture.supplyAsync<br>(()-&gt;&quot;5&quot;).thenAccept(result -&gt; System.out.println(result));</pre><ul><li><strong>thenRun</strong></li></ul><p>“thenRun” can be used where you want to trigger something after Thread completes it’s work but don’t care about the result returned.</p><pre>CompletableFuture&lt;Void&gt; thenRun(Runnable action)</pre><p>thenRun doesn’t has any specific use case but you can club this one with thenApply</p><pre>CompletableFuture&lt;Void&gt; cf = CompletableFuture.supplyAsync<br>(()-&gt;&quot;5&quot;).thenAccept(result -&gt; System.out.println(result))<br>.thenRun(()-&gt;System.out.println(&quot;Operation Successful&quot;));</pre><ul><li><strong>thenCombine</strong></li></ul><p>The Method definition says.</p><pre>CompletableFuture&lt;V&gt; thenCombine(CompletionStage&lt;U&gt; other, BiFunction&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html"><strong>T</strong></a>,U,V&gt; fn)</pre><p>Breaking the method definition. It says it takes two parameters.</p><ol><li><strong>CompletionStage&lt;U&gt; </strong>(Think this as a CompletableFuture)</li><li><strong>BiFunction&lt;T,U,V&gt; </strong>( Same as Function but takes two Argument(Bi))</li></ol><p>“thenCombine ”method returns CompletableFuture&lt;V&gt; meaning the return type (&lt;V&gt;) will be the same as return type specified in the BiFunction.</p><p>“thenCombine” method can be used in the where you want to execute two <strong>CompletableFuture </strong>and use the result of both at once.<br>Both the CompletableFuture runs on <strong>different thread </strong>and once both the work has been completed and result will be passed to <strong>BiFunction</strong>.</p><pre>CompletableFuture.<em>supplyAsync</em>(()-&gt;{<br>    //get Data From Supplier 1;<br>}).thenCombine(CompletableFuture.<em>supplyAsync</em>(()-&gt;{<br>    //get Data From Supplier 2;<br>}),(s1,s2)-&gt;{<br>    //combine the data from s1 and s2 and return something.<br>});</pre><pre><strong>//This can also be cone using the thenApply as</strong></pre><pre>CompletableFuture.<em>supplyAsync</em>(() -&gt; {<br>    //get Data From Supplier 1;<br>}).thenApply(s1 -&gt; {<br>    //get Data from Supplier 2;<br>    //combine s1 and s2;<br>});</pre><p>The downside of using “thenApply ” this way is that the same Thread makes two calls which will decrease the performance. ( there is no multiple threads)</p><ul><li><strong>thenCompose</strong></li></ul><pre>CompletableFuture&lt;U&gt; thenCompose(Function&lt;T, CompletionStage&lt;U&gt;&gt; fn)</pre><p>“thenCompose” takes a “Function” (Functional Interface) as argument that has to return new “CompletableFuture”.</p><p><em>You will need thenCompose in the cases when you want to execute a method that takes the result of first CF and returns a new CF.<br></em>for example if you want to <strong>insert </strong>a record in the database and <strong>fetch </strong>the same record after the insertion.</p><pre>public static CompletableFuture&lt;Long&gt; insertEmployee(){<br>    return CompletableFuture.<em>supplyAsync</em>(()-&gt;{<br>        //insert Data and return Id;<br>    });<br>}<br><br>public static CompletableFuture&lt;Employee&gt; getEmployee(Long id){<br>    return CompletableFuture.<em>supplyAsync</em>(()-&gt;{<br>        //fetch data from DB for Id;<br>    });<br>}</pre><pre>CompletableFuture&lt;Employee&gt; employee = <em>insertData</em>()<br>        .thenCompose(id -&gt; <em>getData</em>(id));</pre><p>This is a not the best example, but I think you can understand. <br>Remember you cannot use thenApply here because thenApply would return <br><strong>CompletableFuture&lt;CompletableFuture&lt;Employee&gt;&gt;</strong></p><pre>CompletableFuture&lt;CompletableFuture&lt;Employee&gt;&gt; completableFutureCompletableFuture = <em>insertData</em>()<br>        .thenApply(id -&gt; <em>getData</em>(id));</pre><ul><li><strong>thenAcceptBoth</strong></li></ul><pre>CompletableFuture&lt;Void&gt; thenAcceptBoth(CompletionStage&lt;U&gt; BiConsumer&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html">T</a>,U&gt; action)</pre><p>It is similar to “thenAccept”, just it has the capacity of “thenCombine”. <br>It takes a new CF as first Argument and BiConsumer as a second argument. The BiConsumer gets the result of both the CFs as input once the CFs are completed. <br>As it is a consumer so it doesn’t has to return anything. It returns void.</p><ul><li><strong>applyToEither</strong></li></ul><pre>CompletableFuture&lt;U&gt; = applyToEither(CompletionStage&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html">T</a>&gt; other,Function&lt;T,U&gt; fn)</pre><p>This method takes a new CF as input of the <strong>same type</strong> as first argument and a “Function” as a second argument. Both the CFs start their work. The Function in the second parameter will be execute for the one who completes the work first.</p><pre>CompletableFuture&lt;Result&gt; cf = getLateshNewsFromCNN()<br>        .applyToEither( getLateshNewsFromBBC(), data -&gt; {<br>         return transform(data));}</pre><p>We can use this method to execute two CompletableFuture which has same work but may have different execution time and you only care about who completes the operation fast. Like fetching news from BBC or CNN, who ever fetches fast we are going to transform and return the data.</p><ul><li><strong>runAfterBoth</strong></li></ul><pre>CompletableFuture&lt;Void&gt; runAfterBoth(CompletionStage&lt;?&gt; other,<br>                                            Runnable action)</pre><p>You can use this method if you want to execute some piece of code after two CFs has completed the work and you don’t want result of the CFs. <br>The First parameter is the new CompletableFuture and the Second parameter is of Runnable type. The Runnable type will run once both the CF finishes the work.</p><ul><li><strong>acceptEither</strong></li></ul><pre>CompletableFuture&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Void.html">Void</a>&gt; acceptEither(  CompletionStage  &lt;T&gt;   other,Consumer&lt;T&gt; action)</pre><p>It is similar to “applyToEither” just that it accept rather than apply, i.e. it’s second argument is of type Consumer not Function so it doesn’t return anything.</p><ul><li><strong>join</strong></li></ul><p>“join” is similar to the join method of our Multi-threading. The Thread <strong>from which</strong> the join method is called will wait until the Thread <strong>on which </strong>the join is being called has completed.</p><pre>public static void main(String[] args){<br>   CompletableFuture&lt;String&gt; cf = CompletableFuture<br>   .supplyAsync(()-&gt;&quot;Hello&quot;);</pre><pre>   String str = cf.join();<br>}</pre><p>Here the join method is called from main thread and join method is being called on cf, so main thread will wait until cf completes it’s work.</p><blockquote><strong>Quick Note:<br>-</strong>Most of the methods has Async version also.<br>-Most of the method supports one extra parameter of type Executor for executing those method in other Thread Pool.</blockquote><ul><li><strong>allOf and anyOf</strong></li></ul><pre>public static CompletableFuture&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Void.html">Void</a>&gt; allOf(CompletableFuture&lt;?&gt;... cfs)</pre><pre>public static CompletableFuture&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Void.html">Void</a>&gt; anyOf(CompletableFuture&lt;?&gt;... cfs)</pre><p>In both the <strong>static method </strong>you can pass many completableFuture. The return type of the method is CompletableFuture&lt;Void&gt;. <br>This returned CompletableFuture will complete if all of the supplied CompletableFuture in method <strong>“allOf()”</strong> completes,<br>and in the case of <strong>“anyOf()” </strong>the CompletableFuture returned will complete if any of the supplied CompletableFuture completes <em>(read that again)</em>.</p><p>You cannot get the result of the supplied CFs. You can use this method if your uses cases doesn’t require the result and depends upon their status.</p><p><strong>Q. get() method in the CompletableFuture is also a blocking operation so how using CompletableFuture is better than using Future.</strong></p><p>Java has designed CompletableFuture in such a way that most of the use case can be tackled without getting the value. <br>It has provided with various method that can be used to perform desired activity without blocking the code. <br>Like passing the result to another function, execution a new CompletableFuture. Combining the result of Two CompletableFuture, handling Exception and lot more.</p><p>Thank You for Reading the Post. I will cover the Exception Handling in next article. Till than <em>Keep Learning</em></p><p><strong>References.</strong></p><ul><li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html">https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html</a></li><li><a href="https://stackoverflow.com/questions/46060548/completablefuture-thenapplyasync-vs-thencompose-and-their-use-cases">https://stackoverflow.com/questions/46060548/completablefuture-thenapplyasync-vs-thencompose-and-their-use-cases</a></li><li><a href="https://www.youtube.com/watch?v=ImtZgX1nmr8">https://www.youtube.com/watch?v=ImtZgX1nmr8</a></li><li><a href="https://www.baeldung.com/java-completablefuture">https://www.baeldung.com/java-completablefuture</a></li><li><a href="https://medium.com/@Mumuksia/completablefuture-practical-guide-e4564f332f83">https://medium.com/@Mumuksia/completablefuture-practical-guide-e4564f332f83</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d522acd89799" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda’s and Functional Programming In Java]]></title>
            <link>https://medium.com/@jajodiatushar/lambdas-and-functional-programming-in-java-39dc8275f183?source=rss-670af1b7a18f------2</link>
            <guid isPermaLink="false">https://medium.com/p/39dc8275f183</guid>
            <category><![CDATA[lambda-expressions]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[java-8-feature]]></category>
            <dc:creator><![CDATA[Tushar Jajodia]]></dc:creator>
            <pubDate>Mon, 02 Mar 2020 10:28:29 GMT</pubDate>
            <atom:updated>2020-03-02T10:28:29.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EvTkMS9poTcc9Qliet1Rng.png" /></figure><p>It’s been a while since java has introduced functional programming, and everyone is using it. When I was new to java’s functional programming it took me a lot of time to understand what was going around and why were the things the way they were.</p><p>In this post I am going to describe you how java has implemented Lambda functions using something that was already there in java.</p><h4>Interface In Java:</h4><p>Interfaces are like the classes with just the signature of the methods without it’s implementation. Interface is a contract, and the classes implementing the interface has to provide the implementation for all the abstract methods. <br>Learn More about Interfaces in this <a href="https://medium.com/s/javaforhumans_1509490998109/java-for-humans-abstract-classes-interfaces-aa4b2ee37418">post</a>.</p><h4>Implementing Interfaces Using Anonymous Inner Classes:</h4><p>If you don’t want to write the class and implement the interface, java provides you to quickly implement the interface with anonymous classes.</p><p>A simple Interface with two methods.</p><pre>public interface Foo {</pre><pre>    void printFoo();</pre><pre>    void printHello();<br>}</pre><p>For implementing above interface with anonymous inner classes.</p><pre>public class Main {<br><br>    public static void main(String[] args)<br>    {<br>        Foo foo = new Foo() {<br><br>            @Override<br>            public void printFoo() {<br>                System.<em>out</em>.println(&quot;Foo&quot;);<br>            }<br><br>            @Override<br>            public void printHello() {<br>                System.<em>out</em>.println(&quot;Hello&quot;);<br>            }<br>        };<br>    }<br>}</pre><p>There is nothing fancy about the above implementation. <br>Java will under the hood generate a class that implements the “Foo Interface”, as the class is implementing the “Foo Interface” it has to provide the implementation for the methods in the “Foo Interface”. <br>It will also create a new instance of that particular class and assign it to the variable foo of type “Foo”</p><p>Now if you only have one method in the interface. Then you can beautify this anonymous inner class implementation. You don’t need to specify the method name ( as java will knows you are writing the implementation for one and only method of the interface)</p><blockquote><strong>These types of interface that has only one abstract method are called Functional Interface in java</strong>. and you can use Lambda functions to provide the implementation for these types of Interfaces.</blockquote><pre>public interface Hero {<br>    void printHero();<br>}</pre><p>The Implementation of the above Interface is.</p><pre>Hero hero = new Hero() {<br>    @Override<br>    public void printHero() {<br>        System.<em>out</em>.println(&quot;Hero&quot;);      <br>    }<br>};</pre><pre>// You don&#39;t need this much lines of code.</pre><pre>Hero hero = ()-&gt; System.<em>out</em>.println(&quot;Hero&quot;);</pre><p>Where is the “new” keyword the “method signature” the “{ }” and everything. <br>this is the optimization. This is lambda function.</p><p>Let me explain you each and every syntax in the lambda function.</p><pre>()-&gt; System.<em>out</em>.println(&quot;Hero&quot;);</pre><pre>The starting &quot;( )&quot; should match the method arguments. <br>if the method for which we are providing the implementation was taking the arguments we had to provide arguments in there like</pre><pre>(a)-&gt; System.<em>out</em>.println(a);</pre><pre>No need to provide the type of the argument. (Java is smart)</pre><pre>the &quot;-&gt;&quot; means it is java&#39;s way of denoting lambda function <br>some other programming language uses =&gt;</pre><pre>There are certain rules in lambda function like when to use &quot;{ }&quot; and &quot;return&quot; statement.</pre><pre>If we had more than one line of code in the lambda function we would need to use the &quot;{ }&quot;</pre><pre>like</pre><pre>(a) -&gt; {<br>   System.<em>out</em>.println(&quot;Hero&quot;);<br>   System.<em>out</em>.println(a);<br>}</pre><pre><br>If our method signature was returning something then we need to return something from the lambda function as well,<br>like</pre><pre>(a) -&gt; {<br>   System.<em>out</em>.println(&quot;Hero&quot;);<br>   System.<em>out</em>.println(a);<br>   return a % 2;<br>}</pre><pre>If we only had one line of code in lambda and return statement then no need to use return keyword,<br>like</pre><pre>(a) -&gt; a % 2 == 0;</pre><pre>this is equivalent to </pre><pre>(a) -&gt; {<br>return a % 2 == 0;<br>}</pre><pre>or </pre><pre>(a) -&gt; {<br>   a % 2 == 0 <br>}</pre><p>So Lambda’s in java are nothing but a shorthand implementation of Interfaces that only has one method.</p><p><strong>What is the benefit of using the Lambdas ?</strong><br>Well you can quickly write the small function where you don’t want to define all this method signature return type and all the fuss.</p><p>But wait, <strong><em>to write the Lambda function in java you will need to have Functional Interfaces</em></strong>. <br>Without interfaces you can’t write lambda function.<br>So, Firstly you will need to make Interface as per your need and then write the Lambda function.<br>Isn’t it contradicting the reason for why we are using lambda function.<br><em>(quick and easy).</em></p><p>So Java provide a package <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html">java.util.Function</a> with a lot of Functional Interfaces which you can use to write lambda function as implementation of these Interfaces.</p><h3>Some of the Mostly used Functional Interfaces are</h3><h4>Consumer :</h4><pre>public interface Consumer&lt;T&gt;{<br>    void accept(T t);<br>}</pre><p>This interface has only one abstract method “accept”. This method takes one input and doesn’t return anything. You can easily provide the implementation using lambdas like.</p><pre>Consumer&lt;String&gt; customConsumer = str -&gt; System.out.println(str);</pre><pre>// To Call this method you need to do this. </pre><pre>customConsumer.accept(&quot;Medium&quot;);</pre><p>So when you need to write the lambda function where you need to take one argument and return void you can use this Functional Interface. Like in the forEach method of the stream.</p><pre>list.stream().forEach(customConsumer);<br>//or<br>list.stream().forEach(str-&gt;System.out.println(str));</pre><h4>Function :</h4><pre>public interface Function&lt;T,R&gt;{<br>     R accept(T t);<br>}</pre><p>This interface also has only one abstract method “accept” that takes one argument as input and returns one as output. You can use this Functional Interface to provide the implementation for the “map” method in of the stream.</p><pre>Function&lt;String,Integer&gt; customFunction = str -&gt; Integer.parseInt(str);</pre><pre><br>list.stream().map(customFunction)</pre><pre>//or</pre><pre>list.stream().map( str-&gt; Integer.parseInt(str))</pre><h4>Supplier :</h4><pre>public interface Supplier&lt;T&gt;{<br>   T get()<br>}</pre><p>This interface provides one abstract method which takes no argument but returns one argument. If you have such requirement you can implement this Interface.</p><p>For Eg.</p><pre>Supplier&lt;Date&gt; customSupplier = ()-&gt; new Date();</pre><pre>customSupplier.get() // will return new Date everytime you call</pre><h4>Predicate :</h4><pre>public interface Predicate&lt;T&gt;{ <br>    boolean test(T t);<br>}</pre><p>This interface is similar to the Function Interface which takes one Input argument and returns boolean. You can use this Functional Interface to provide the implementation for the filter method of the stream.</p><pre>Predicate&lt;String&gt; customPredicate = str -&gt; str.length() &gt; 10;</pre><pre>list.stream().filter(customPredicate)</pre><pre>//or</pre><pre>list.stream().filter(str -&gt; str.length() &gt; 10);</pre><p>Beside this there are a lot of the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html">Functional Interface </a>.</p><p>This was the short article on Java’s Functional Programming.<br>There is a lot more to be covered and I hope to cover them in the future articles. <em>Keep Learning</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39dc8275f183" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>