<?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 Sreenidhi KV on Medium]]></title>
        <description><![CDATA[Stories by Sreenidhi KV on Medium]]></description>
        <link>https://medium.com/@codesnoob?source=rss-ba9c1723bcd9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hsVABfcrwowklMqCOxJ8JQ.jpeg</url>
            <title>Stories by Sreenidhi KV on Medium</title>
            <link>https://medium.com/@codesnoob?source=rss-ba9c1723bcd9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:38:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codesnoob/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[Scratchpad — Reliable Scalable and Maintainable Applications (DDIA CH-1)]]></title>
            <link>https://codesnoob.medium.com/scratchpad-reliable-scalable-and-maintainable-applications-ddia-ch-1-5b91b9e971d8?source=rss-ba9c1723bcd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b91b9e971d8</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[dia-d]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <dc:creator><![CDATA[Sreenidhi KV]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 16:23:06 GMT</pubDate>
            <atom:updated>2026-10-22T16:25:04.882Z</atom:updated>
            <content:encoded><![CDATA[<p>Got the feels to get back to reading DDIA. This will be a WIP.<br>Writing down my thoughts, learnings, ToDos etc here</p><p>Data intensive?<br>- Data is primary challenge<br>- Quantity of data<br>- Complexity of data<br>- Speed at which data changes</p><p>Compute Intensive?<br> — CPU cycles are bottleneck</p><p>Problems/Patterns wrt data<br> — Store data (Databases)<br> — Remember expensive operations (cache)<br> — Search by keyword/Filter (search index)<br> — Async handling (stream processing)<br> — Crunch data periodically (batch process)</p><p><strong>Thinking About Data Systems<br>- </strong>Datastores can now be used a msg queues (redis)<br>- Msg queues with DB like durability (kafka)</p><p>Questions to think about<br> — How will data remain correct + complete even when things go wrong?<br> — How to provide consistent good performance?<br> — How to scale when load increases?<br> — What does a good API look like?</p><p>Reliability<br> — Systems should continue to work correctly (perfrom correct function with desired performance) even in face of adversity (h/w, s/w and human faults or error)</p><p>Scalability<br> As system grows (data volume, traffic volume, complexity) there should be ways to deal with the growth.</p><p>Maintainability<br> Diff people work on system + all work productively</p><p><strong>Reliability</strong></p><ul><li>App performs as expected</li><li>tolerate user mistakes</li><li>Performance should be good enough under load</li><li>prevent any unauthorised access</li></ul><p>Reliability = continuing to work correctly even when things go wrong Things that can go wrong = faults<br> systems that anticipate faults and cope with them = fault tolerant systems<br> Fault != failure<br> Fault = system deviating from spec<br> failure = systems stops providing service to user<br> Cannot reduce fault to 0, so try to build fault tolerant systems<br> trigger faults in your system (<em>TODO: Netflix chaos monke</em>y)</p><p>Fault Types<br> — h/w<br> — s/w<br> — human error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EidcrCO1rSLT8UvY" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b91b9e971d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Internals of annoying everyone by using @here/@everyone/@all]]></title>
            <link>https://codesnoob.medium.com/internals-of-annoying-everyone-by-using-here-everyone-all-e6f12c14ace9?source=rss-ba9c1723bcd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6f12c14ace9</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Sreenidhi KV]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 14:28:44 GMT</pubDate>
            <atom:updated>2026-04-22T14:28:44.397Z</atom:updated>
            <content:encoded><![CDATA[<p>Tis the szn for a blog, rolling out with a easy breezy system breakdown.<br>Let’s understand the beauty behind annoying people by tagging everyone in a group for absolutely no reason.</p><p>In Slack/Discord/Teams we can broadcast unsolicited thoughts to the world with a mere @. Time to dig down the How’s, What’s and Why’s.</p><h4>What does @here/@everyone/@all do?</h4><p>It broadcasts the intended message to all the participants who are part of the channel/group.</p><blockquote>The above statement has multiple steps within it, in other words, the flow will look something like this<br>- User creates a group chat<br>- Multiple participants can be added to the group chat <br>- Any user can broadcast a message<br>- Message will be received by all participants</blockquote><blockquote>How many users are we looking at? <br>Let’s start with the naive way. With just a couple of participants (n = 10) and scale up.</blockquote><blockquote>What exactly is the “Message” we will be playing with for the blog?<br>User wants to broadcast a “I’ve fallen sick, so taking the day off” message on a fine Monday Morning. Aka start with text and extend it to media.</blockquote><h4>How does this work? How can I design it?</h4><p>Before jumping to scale. <br>Let’s identify the core entities of our system and what actions they can perform.</p><p>Based on the flow, we have — User, Message, Chat, Chat_Participants as core entities.</p><blockquote>- <strong>User</strong> creates a group <strong>chat<br></strong>- Multiple <strong>participants</strong> can be added to the group chat <br>- Any user can broadcast a <strong>message</strong><br>- Message will be received by all participants</blockquote><p>The next logical step will be to think of entities from DB perspective. Let’s assume the entities will be mapped to a DB schema as below. (Nothing is set in stone we will keep modifying as our heart pleases.)</p><pre>Chat(chat_id, chat_name,...)<br>User(user_id, user_name, ...)<br>Message(message_id, message, user_id, ...)<br>Chat_Participants(chat_id, user_id, ...)</pre><p>Now let’s identify the possible actions performed by the users.<br>- Group Chat Creation<br>- Adding participants<br>- Sending Message<br>- Receiving Message<br>Note: We can always follow better API protocols just to get the ball running let’s go with the below bare basics 😉.</p><p>1) Group Chat creation can be done via the below API call<br>POST /chats/create</p><pre>JWT of user_id_1<br>POST /chats/create<br>Request <br>Chat<br>{<br>    &quot;name&quot;: &quot;very_important_stuff&quot;<br>}<br>Response <br>Chat + User<br>{<br>    &quot;chat_id&quot;: 1,<br>    &quot;name&quot;: &quot;very_important_stuff&quot;,<br>    &quot;chat_participants&quot;: [&quot;user_1&quot;]<br>}  <br><br>DB entries for above API call<br>Chat(chat_id_1, very_important_stuff,...)<br>Chat_participant(chat_id_1,user_id_1,...)<br>User(user_id_1,User A)</pre><p>2) Participants can be added to the group chat via the below API call<br>POST /chats/{id}/users</p><pre>JWT of user_id_1<br>POST /chats/1/users<br>Request User<br>{<br>    &quot;users&quot;: [&quot;user_2&quot;, &quot;user_3&quot;]<br>}<br>Response -&gt; Chat + User<br>{<br>    &quot;chat_id&quot;: 1,<br>    &quot;name&quot;: &quot;very_important_stuff&quot;,<br>    &quot;chat_participants&quot;: [&quot;user_1&quot;, &quot;user_2&quot;, &quot;user_3&quot;]<br>}  <br>in the DB entries will be created<br>Chat_participant(chat_id_1,user_id_2,...)<br>Chat_participant(chat_id_1,user_id_3,...)<br><br>User(user_id_2,..)<br>User(user_id_3,..)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fy44TgRSRpBHzgQORLLl9w.png" /></figure><p>3) Sending Message <br>Absolute noob way would be to use a REST call like <br>POST /chats/{id}/message and let’s go with that.</p><blockquote>What would be the realistic way if not REST?<br>How will I send media here? <br>What if the media is large? <br>(Hold your horses will extend the system later)</blockquote><pre>JWT of user_1<br>POST /chats/1/messages/send<br>Request Message<br>{<br>    &quot;message&quot;: &quot;I&#39;ve fallen sick, so taking the day off&quot;<br>}<br>Response -&gt; 200 OK<br><br>in the DB entries will be created<br>Messages(chat_id_1, I&#39;ve fallen sick, so taking the day off, user_id_1)</pre><p>4) Receiving Message<br>Since we have walked down the REST road. Each user who is part of the group chat needs to consistently poll. Go on friend, keep hitting the receive endpoint at fixed intervals to get the latest messages. <br>GET /chats/1/messages/receive</p><pre>JWT of user_2<br>GET /chats/1/messages/receive<br>Response Message<br>{<br>    &quot;messages&quot;: [&quot;I&#39;ve fallen sick, so taking the day off&quot;]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9D8wnFlTCg4qHJjrW0EiA.png" /></figure><blockquote>Thoughts for fun!<br>1) GET calls keeps happening even if no broadcast/message has been sent. <br>2) Along with GET call we need to keep tabs of how much each user has read so that the next call does not need to get all messages. <br>I can persist the latest message read by each user and then return only unread messages. Latest message can be identified by a state added to each message (READ, UNREAD) or I can do pagination and store id’s of latest read. Okay, that does work, but it is indeed a lot of work.<br>3) What if receiver is offline? What happens to the broadcasted message? Where does it go? Hmm, how can I know if a user is offline? REST does not help here at all. <br>4) Is there a better way to maintain connection also not constantly poll?<br>Websockets to the rescue, Websockets are persistent connections between client and server.<br>5) What is websocket how does it solve this problem?</blockquote><p>Keep pondering, don’t @ me.<br>I’ll be back tomorrow to finish my thoughts. <br>Thanks :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aBb8l1FXl0HnIGu8" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6f12c14ace9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autocomplete System]]></title>
            <link>https://codesnoob.medium.com/autocomplete-system-811fa82431db?source=rss-ba9c1723bcd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/811fa82431db</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Sreenidhi KV]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 04:27:23 GMT</pubDate>
            <atom:updated>2025-08-18T04:27:23.221Z</atom:updated>
            <content:encoded><![CDATA[<p>WIP but zoom in and enjoy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yQH0oIR5QnwlFOiFUOAwg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=811fa82431db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chat System]]></title>
            <link>https://codesnoob.medium.com/chat-system-aff02b6e11cb?source=rss-ba9c1723bcd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/aff02b6e11cb</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Sreenidhi KV]]></dc:creator>
            <pubDate>Fri, 15 Aug 2025 11:52:58 GMT</pubDate>
            <atom:updated>2025-08-15T11:52:58.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0H6vNTpsSDjSVE3UMflE2A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aff02b6e11cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notification System]]></title>
            <link>https://codesnoob.medium.com/notification-system-c3e7687a1ab3?source=rss-ba9c1723bcd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3e7687a1ab3</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Sreenidhi KV]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 03:10:21 GMT</pubDate>
            <atom:updated>2025-08-14T13:41:27.878Z</atom:updated>
            <content:encoded><![CDATA[<p>Updating on a daily basis, zoom in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOJJOAcZB4W3INewPIpGlg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3e7687a1ab3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Key Value Store]]></title>
            <link>https://codesnoob.medium.com/distributed-key-value-store-819a71125477?source=rss-ba9c1723bcd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/819a71125477</guid>
            <category><![CDATA[key-value-store]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Sreenidhi KV]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 11:32:41 GMT</pubDate>
            <atom:updated>2025-07-14T13:54:58.382Z</atom:updated>
            <content:encoded><![CDATA[<p>Planning to update my thoughts here regularly :)<br>Zoom in and Enjoy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvIxcIVre8iNZr--GiFgFg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=819a71125477" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dark Channel Prior]]></title>
            <link>https://codesnoob.medium.com/dark-channel-prior-d933c36a9ead?source=rss-ba9c1723bcd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d933c36a9ead</guid>
            <category><![CDATA[dcp]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Sreenidhi KV]]></dc:creator>
            <pubDate>Thu, 09 May 2024 16:33:25 GMT</pubDate>
            <atom:updated>2024-05-09T16:36:58.440Z</atom:updated>
            <content:encoded><![CDATA[<p>Work In Progress :-)<br>Publishing it so that I hold myself accountable!<br>Can’t wait to blog more this year!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*MTW3l5xBxUK_xfwf.gif" /></figure><p>Hazy Image = Airlight + Attenuation</p><p>Hazy Image = I<br>Airlight = A (1 — t(x))</p><blockquote>A = Atmospheric light<br>x = Image coordinates</blockquote><p>Attenuation = (J(x))(t(x))</p><blockquote>J = Haze free image/ object currently being observed/ Actual image<br>x = Image coordinates</blockquote><p>Where<br>t(x) = e^-(β d(x)) <br>Is also known as transmission map</p><blockquote>β = scattering coeff of atmosphere <br>d = distance of camera from image</blockquote><blockquote>I = J (x)* t(x) + A (1- t(x))</blockquote><blockquote>t(x) = e^-(β d(x))</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*dI9Bma1BLqY27q5QXt10_w.png" /></figure><ol><li>Weather is clear/ideal <br>β = 0<br>I = J</li><li>Weather is not clear/ideal<br>β != 0<br>I != J</li><li>Attenuation decreases as distance/depth increases</li><li>Airlight increases ad depth increases</li><li>A and t should be estimated correctly to dehaze the image</li><li>Goal — Recover J from I</li></ol><p>Goal can be achieved after getting A and t and replacing the above formula</p><blockquote>J(x) = (I — A)/(t(x)) +A</blockquote><ul><li>How can you figure out the depth/distance from an image?<br>It’s equal to the number of pixels.</li></ul><blockquote>What’s the correlation btw depth and pixel? <br>Based on pixel the distance of objects can be identified. Farther objects will appear darker and smoother and closer objects appear brighter and have more texture</blockquote><ul><li>How to figure out dark channel?<br>There is always one band/image channel (R or G or B) that will have pixels close to 0. <br>0 = devoid of light</li><li>What causes dark channel to have low intensity?<br>Shadows, Colourful surface, Dark surface ?? //TODO double check validity</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*XP_0U1TyAWG3IgjKS0WnWQ.png" /></figure><blockquote>Jc(y) = intensity of channel (R or G or B)<br>Ω(x) = local patch centered at pixel x</blockquote><ul><li>What is local patch?<br>Rather than analysing all the pixels in one go, the image is broken down into grids. For each grid we get the min pixel of that patch.<br>The min value present in R/G/B channel among the patch is chosen as dark channel J dark.</li><li>Why local patch?<br>If an image has 9 patches (9 grids/ 9 mini rectangles), you’ll get 9 J dark values. Better than getting one J dark value if you analyse the entire image in one go. Better accuracy</li></ul><p>Ideal case J dark = 0 (nearly)</p><ul><li>Why use dark channel if J dark is nearly 0?<br>Atmosphere changes game, it will not make it near to 0. Atmospheric light is bright and achromatic, thus never making dark channel near to 0 in local patches.</li></ul><p>How to enhance image by dehazing using DCP channels?<br>1. Find atomsperic light value per patch A for each channel<br>2. Divide each image patch (pixel patch) by atmospheric light<br>3. Get min value per patch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*xvDI7OkV5qEye57bk9jWjQ.png" /></figure><p>Resolve to get final image from dark image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*RlI8esR92Nuoe_MCodyCAw.png" /></figure><blockquote>t0 = lower bound</blockquote><p>Why max among 2 transmission maps? //TODO</p><p>TODO</p><ol><li>How to determine atmospheric light value from image? — read paper</li><li>Transmissing map estimation t(x) — read paper</li><li>How to get lower bound?</li><li>Refining images</li><li>soft matting and filters</li></ol><p>References <br>1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nQYnbomnP3aqYHRF" /><figcaption>Adding my signature pineapple! How can I miss it huh?</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d933c36a9ead" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 8 — Local Variables and Lambda Function]]></title>
            <link>https://codesnoob.medium.com/java-8-local-variables-and-lambda-function-4ce96f80c97a?source=rss-ba9c1723bcd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ce96f80c97a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Sreenidhi KV]]></dc:creator>
            <pubDate>Mon, 17 May 2021 10:24:20 GMT</pubDate>
            <atom:updated>2022-06-10T02:45:07.798Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 8 — Local Variables and Lambdas</h3><p>Let’s break down how to consume local variable with lambda functions in java</p><p>The following scenarios will be covered,</p><ol><li>Lambda consumes local variable initialized in a method</li><li>Local variable initialized in the Lambda function</li><li>Manipulating local variable inside the lambda function</li><li>Manipulating local variable outside the lambda function</li><li>Lambda functions consuming local reference variable</li><li>Declaring variables inside the lambda function</li><li>Using This in Lambda</li><li>Naming Convention in Lambda</li></ol><h3>Lambda and Local Variables</h3><p>Let’s take the case where a variable is being consumed by Lambda</p><p>Let’s take a class (<strong><em>Doge</em></strong>) that consumes a Functional Interface (<strong><em>PrintCoin</em></strong>) which prints the number of coins.</p><p>The Functional Interface look like this, which takes a single abstract method <strong><em>print()</em></strong></p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}</pre><p>The Class <strong><em>Doge</em></strong> looks like this, we define the function as</p><blockquote><strong>() -&gt; System.<em>out</em>.println(&quot;Hey Gurl! I see dem coins. I got &quot;+coin+&quot; coins&quot;);</strong></blockquote><p>which gets mapped to <strong><em>print()</em></strong></p><pre>class Doge{<br><br>    public void getDoge(){<br>        int coin = 100;<br>        PrintCoin printCoin = () -&gt; System.<em>out</em>.println(&quot;Hey Gurl! I see dem coins. I got &quot;+coin+&quot; coins&quot;);<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>The output will look like this</p><pre>Hey Gurl! I see dem coins. I got 100 coins</pre><p>Super simple! The lambda just consumes the value.</p><p>Voila! It just gets super easy from here!</p><h3>Local variable initialized in a method</h3><p>Just like in the above example, the local variable coin is consumed by the lambda,</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    public void getDoge(){<br>     <strong>   int coin = 100; //local variable</strong><br>        PrintCoin printCoin = () -&gt; System.<em>out</em>.println(&quot;Hey Gurl! I see dem coins. I got &quot;+<strong>coin</strong>+&quot; coins&quot;); <strong>//lambda consumes it</strong><br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output</p><pre>Hey Gurl! I see dem coins. I got 100 coins</pre><h3>Local variable initialized in the Lambda function</h3><p>Now let’s try and change the variable inside the lambda function</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    public void getDoge(){<br>        int coin;<br>        PrintCoin printCoin = () -&gt; {<br>         <strong>   coin = 100; // Compile Time Error</strong><br>            System.<em>out</em>.println(&quot;Hey Gurl! I see dem coins. I got &quot;+coin+&quot; coins&quot;);<br>        };<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output</p><pre>java: local variables referenced from a lambda expression must be final or effectively final</pre><p>Whoa! What just happened?</p><p>Let’s break down all the questions scramming in our heads!</p><blockquote><strong>What is effectively final?</strong></blockquote><blockquote>Without having to explicitly say that a variable is final, i.e unlike</blockquote><blockquote><strong>final int number = 30;</strong></blockquote><blockquote>where we have explicitly declared final. Incase of effectively final we won’t have to declare <strong>final </strong>keyword.</blockquote><blockquote>Final variable insinuates that it’s a constant and will never change. The same applies for effectively final. Except the compiler now can understand that it’s final without us having to explicitly write the final keyword it. Which means after initialization the value will never change.</blockquote><blockquote><strong>Why do local variables need to be final or effectively final?</strong></blockquote><blockquote>To ensure that no concurrency issues occur.</blockquote><blockquote><strong>How can concurrency issues occur because of local variables?</strong></blockquote><blockquote>Let’s say multiple threads are working on the method. Maintaining a consistent value for the variable gets difficult. The value of the variable is unpredicatble. Depending on the thread executing the value changes. So to deal with concurrent operations the local variables are final or effectively final.</blockquote><blockquote><strong>Does this occur for static and instance variables too (</strong><a href="https://codesnoob.medium.com/java-8-instance-variables-and-lambdas-71b5cb81b61d"><strong>Instance Variable</strong></a><strong>, </strong><a href="https://codesnoob.medium.com/static-variables-and-lambdas-ee16c2a0211e"><strong>Static Variable</strong></a><strong>)?</strong></blockquote><blockquote><strong>NOPE!</strong></blockquote><blockquote><strong>Why does it not occur for Static or Instance Variables?</strong></blockquote><blockquote>Let’s talk about the memory storage of the variables,</blockquote><blockquote>Instance variables are stored in the heap area. Static variables previously were stored in PermGen (method area) and now in Metaspace. Local variables are stored on the stack.</blockquote><blockquote>What does this have got to do?</blockquote><blockquote>The stack reference is unique to each thread so the local variables are not common to each thread, whereas instance and static variables are commonly available and at all times their values will be consistent for each thread. In short, the location of where the variables are being placed is the reason why static and instance variables don’t face the issue.</blockquote><h3>Manipulating local variable outside the lambda function</h3><p>Let’s have the lambda consume coin, but let’s manipulate the value outside the lambda as shown,</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    public void getDoge(){<br>        int coin = 100;<br>        PrintCoin printCoin = () -&gt; {<br>            System.<em>out</em>.println(&quot;Hey Gurl! I see dem coins. I got  coins&quot; + <strong>coin</strong>); <strong>//lambda consumes coin</strong><br>        };<br>     <strong>   coin ++; //manipulating outside lambda function</strong><br>        System.<em>out</em>.println(coin);<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output?</p><pre>java: local variables referenced from a lambda expression must be final or effectively final</pre><p>Yuck! Again?</p><blockquote><strong>Why?</strong></blockquote><blockquote>As stated above the local variables in lambdas are final or effectively final. Which ensures that the values consumed will always be consistent in a multithreaded environment.</blockquote><p>Okay!</p><blockquote><strong>What if the lambda does not consume the variable?</strong></blockquote><blockquote>Then it works like a normal local variable. As shown below.</blockquote><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    public void getDoge(){<br>        int coin = 100;<br>        PrintCoin printCoin = () -&gt; {<br>            System.<em>out</em>.println(&quot;Hey Gurl! I dont want no coins&quot;);<br>        };<br>       <strong> coin ++; // not consumed by lambda</strong><br>        System.<em>out</em>.println(&quot;Printing coins that are not consumed by lambda = &quot;+ coin);<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>The output looks like this,</p><pre>Printing coins that are not consumed by lambda = 101<br>Hey Gurl! I dont want no coins</pre><p>Sweet!</p><h3>Manipulating Local Variables inside Lambda Functions</h3><p>Let’s manipulate the value of coin inside the lambda function now,</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    public void getDoge(){<br>        int coin = 100;<br>        PrintCoin printCoin = () -&gt; {<br>           <strong> coin ++; //manipulating inside lambda function </strong><br>            System.<em>out</em>.println(&quot;Hey Gurl! I dont want no coins&quot;);<br>        };<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output?</p><pre>java: local variables referenced from a lambda expression must be final or effectively final</pre><p>Why?</p><p>You know it! It’s the same reason all over! EFFECTIVELY FINAL/FINAL, CONCURRENCY Blah Blah!</p><h3>Lambda functions consuming local reference variable</h3><p>Final refers that once initialized we can’t reinitialize.</p><p>The same works for reference we can initialize it once but no reinitialization is allowed.</p><pre>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.List;<br><br>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    public void getDoge(){<br>        int coin = 100;<br>     <strong>   List&lt;Integer&gt; coinsBought = new ArrayList();</strong><br>        PrintCoin printCoin = () -&gt; {<br>           <strong> coinsBought = Arrays.<em>asList</em>(80,20); //compile time error</strong><br>            System.<em>out</em>.println(&quot;Hey Gurl! I dont want no coins&quot;);<br>        };<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output is the same ole,</p><pre>java: local variables referenced from a lambda expression must be final or effectively final</pre><p>No reinitialization allowed for finals/effectively final!</p><blockquote><strong>How to manipulate the local variables of a method, that get’s consumed by Lambda function?</strong></blockquote><blockquote>Can use Atomic References eg, AtomicIntegers which ensures concurrency. Although we shouldn’t be manipulating local variables inside lambdas.</blockquote><blockquote><strong>Can we add values to references?</strong></blockquote><blockquote>Don’t get confused!</blockquote><blockquote><strong>Final ensures that the reference never changes, the value can change! </strong>As shown below.</blockquote><pre>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.List;<br><br>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    public void getDoge(){<br>        int coin = 100;<br>        List&lt;Integer&gt; coinsBought = new ArrayList();<br>        PrintCoin printCoin = () -&gt; {<br>           <strong> coinsBought.add(80); //allowed <br>            coinsBought.add(20);</strong><br>            int value = coin + coinsBought.stream().reduce(0 , (coin1,coin2) -&gt; coin1 + coin2);<br>            System.<em>out</em>.println(value +&quot; Doge coins in my bag!&quot;);<br>        };<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>The output looks like this,</p><pre>200 Doge coins in my bag!</pre><p>Yay!!</p><h3>Declaring Variables Inside Lambda Function</h3><p>Can we declare variables inside Lambda Function? HELL YEAH!</p><p>In the above example, we had done it too! Let’s dig down</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    public void getDoge(){<br>        int coin = 100;<br>        List&lt;Integer&gt; coinsBought = new ArrayList();<br>        PrintCoin printCoin = () -&gt; {<br>            coinsBought.add(80); <br>            coinsBought.add(20);<br>            <strong>int value</strong> = coin + coinsBought.stream().reduce(0 , (coin1,coin2) -&gt; coin1 + coin2); <strong>//declared a variable inside lambda</strong><br>            System.<em>out</em>.println(value +&quot; Doge coins in my bag!&quot;);<br>        };<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output,</p><pre>200 Doge coins in my bag!</pre><p>Can we manipulate the local variable declared inside the lambda function? YES YES AND YES! It’s not final!</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    public void getDoge(){<br>        int coin = 100;<br>        List&lt;Integer&gt; coinsBought = new ArrayList();<br>        PrintCoin printCoin = () -&gt; {<br>            coinsBought.add(80);<br>            coinsBought.add(20);<br>            <strong>int value </strong>= coin + coinsBought.stream().reduce(0 , (coin1,coin2) -&gt; coin1 + coin2);<br>            <strong>value ++;</strong><br>            System.<em>out</em>.println(value +&quot; Doge coins in my bag!&quot;);<br>            <strong>value ++; //can manipulate as it&#39;s not final!</strong><br>            System.<em>out</em>.println(value +&quot; Doge coins ++&quot;);<br><br>        };<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output,</p><pre>201 Doge coins in my bag!<br>202 Doge coins ++</pre><p>Similarly, let’s see with references,</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    public void getDoge(){<br><br>        PrintCoin printCoin = () -&gt; {<br>           <strong> List&lt;Integer&gt; coinsBought = new ArrayList();</strong><br>            coinsBought.add(80);<br>            coinsBought.add(20);<br>            System.<em>out</em>.println(&quot; Doge coins bought = &quot;+coinsBought);<br>           <strong> coinsBought = Arrays.<em>asList</em>(100,200); //no error</strong><br>            System.<em>out</em>.println(&quot; Doge coins bought = &quot;+coinsBought);<br>        };<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output,</p><pre>Doge coins bought = [80, 20]<br>Doge coins bought = [100, 200]</pre><p>Worked!</p><h3>This in Lambda</h3><p>This refers to the current outer reference. Unlike Anonymous classes</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    <strong>int coin = 30; //this referes to current outer value <br></strong>    public void getDoge(){<br>        int coin = 20;<br>        PrintCoin printCoin = () -&gt; {<br>            System.<em>out</em>.println(&quot; Doge coins bought = &quot;+ <strong>this.coin</strong>);<br>        };<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output</p><pre>Doge coins bought = 30</pre><p>How to access the local variable? Remove this! Easy!</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    int coin = 30;<br>    public void getDoge(){<br>        int coin = 20;<br>        PrintCoin printCoin = () -&gt; {<br>            System.<em>out</em>.println(&quot; coin = &quot;+ <strong>coin</strong>);<br>            System.<em>out</em>.println(&quot; this.coin = &quot;+ <strong>this.coin</strong>);<br>        };<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output,</p><pre>coin = 20<br>this.coin = 30</pre><h3>Naming Convention in Lambda</h3><p><em>The local variable name defined inside the method and the local variable name defined inside the lambda function cannot be the same!</em></p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    int coin = 30;<br>    public void getDoge(){<br>       <strong> int coin = 20;</strong><br>        PrintCoin printCoin = () -&gt; {<br>           <strong> int coin = 40; //cannot be the same</strong><br>        };<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output</p><pre>java: variable coin is already defined in method getDoge()</pre><p><em>The local variable name defined inside the method and the parameter name of the lambda function cannot be the same!</em></p><pre>package com.company;<br><br>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.List;<br><br>@FunctionalInterface<br>interface PrintCoin{<br>    void print(int value);<br>}<br><br>class Doge{<br><br>    int coin = 30;<br>    public void getDoge(){<br>       <strong> int coin = 20;</strong><br>        PrintCoin printCoin = (<strong>coin</strong>) -&gt; { <strong>//cannot define same name</strong><br><br>        };<br>        printCoin.print(200);<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output</p><pre>java: variable coin is already defined in method getDoge()</pre><p>You’ve aced Lambdas yay!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-4T5WaUcXBgGicNi" /><figcaption>Pineapples flexing after learning Local Variables in Lambdas</figcaption></figure><p>That’s all folks!</p><p>Play around more! Do Let me know if I missed any scenarios.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ce96f80c97a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 8 — Instance Variables and Lambdas]]></title>
            <link>https://codesnoob.medium.com/java-8-instance-variables-and-lambdas-71b5cb81b61d?source=rss-ba9c1723bcd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/71b5cb81b61d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[java8]]></category>
            <dc:creator><![CDATA[Sreenidhi KV]]></dc:creator>
            <pubDate>Sun, 16 May 2021 17:35:48 GMT</pubDate>
            <atom:updated>2021-05-17T11:14:59.704Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 8 — Instance Variables and Lambdas</h3><p>Let’s break down how to consume instance variable with lambda functions in java</p><p>The following scenarios will be covered,</p><ol><li>Lambda consumes an instance variable initialized in a method</li><li>Lambda consumes an instance variable initialized in the Lambda function</li><li>Lambda functions consuming reference variable</li></ol><h3>Instance Variable and Lambda Function</h3><p>Let’s take the case where a variable is being consumed by Lambda</p><p>Let’s take a class (<strong><em>Doge</em></strong>) that consumes a Functional Interface (<strong><em>PrintCoin</em></strong>) which prints the number of coins.</p><p>The Functional Interface look like this, which takes a single abstract method <strong><em>print()</em></strong></p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}</pre><p>The Class <strong><em>Doge</em></strong> looks like this, we define the function as</p><blockquote><strong>() -&gt; System.<em>out</em>.println(&quot;Here&#39;s your doge = &quot;+coin);</strong></blockquote><p>which gets mapped to <strong><em>print()</em></strong></p><pre>class Doge{<br><br>    int coin;<br><br>    public void getDoge(){<br>        PrintCoin printCoin = () -&gt; System.<em>out</em>.println(&quot;Here&#39;s your doge = &quot;+coin);<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>The output will look like this</p><pre>Here&#39;s your doge = 0</pre><p>Super simple! The lambda just consumes the instance value.</p><p>The default value of coin is 0. Let’s initialize the values.</p><p>Voila! It just gets super easy from here!</p><h3>Instance variable initialized in a Method</h3><p>In the previous example, the coin was initialized with a default value. Let’s initialize the value inside a method.</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    int coin;<br><br>    public void getDoge(){<br>        <strong>coin = 100; //init inside method</strong><br>        PrintCoin printCoin = () -&gt; System.<em>out</em>.println(&quot;Here&#39;s your doge = &quot;+coin);<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>    }<br>}</pre><p>Output,</p><pre>Here&#39;s your doge = 100</pre><p>We can see that the lambda is able to pick up the updated instance variable value within its function.</p><h3>Instance variable initialized inside Lambda</h3><p>Let’s directly initialize the coin value inside the Lambda.</p><p>Can we manipulate the value after initialization? <strong>HELL YES!</strong></p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    int coin;<br><br>    public void getDoge(){<br>        PrintCoin printCoin = () -&gt; {<br>            <strong>coin = 50; //init inside lambda</strong> <br>            <strong>coin = coin + 50; //manipulating value inside lambda</strong><br>            System.<em>out</em>.println(&quot;Here&#39;s your doge = &quot;+coin);<br>        };<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br>        </pre><pre>        <strong>//checking the value after manipulation outside lambda</strong><br>        System.<em>out</em>.println(&quot;Doge value =&quot;+ doge.coin);<br>    }<br>}</pre><p>Output? you know it!</p><pre>Here&#39;s your doge = 100<br>Doge value =100</pre><p>This way we can manipulate and initialize values inside the lambda.</p><h3>Reference Variables and Lambda</h3><p>We will add a List of Integers that define the coins bought.</p><p>Then we will add the total coins bought.</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    int coin;<br><br> <strong>   List&lt;Integer&gt; coinBought = Arrays.<em>asList</em>(80,20); //reference<br><br> </strong>   public void getDoge(){<br>        PrintCoin printCoin = () -&gt; {<br>            coin = 50;<br>            <strong>coin += coinBought.stream().reduce(0, (coin1,coin2) -&gt; coin1+coin2); //summation of list</strong><br>            System.<em>out</em>.println(&quot;Doge to the MOoon! Bag it sis = &quot;+coin);<br>        };<br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br><br>        System.<em>out</em>.println(&quot;Doge value = &quot;+ doge.coin);<br>    }<br>}</pre><p>The output looks like this,</p><pre>Doge to the MOoon! Bag it sis = 150<br>Doge value =150</pre><p>As we can see we have accessed references inside the lambda.</p><p>Perfect!</p><p>Let’s try initializing the reference inside the lambda</p><pre>package com.company;<br><br>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.List;<br><br>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    int coin;<br><br>    List&lt;Integer&gt; coinBought;<br><br>    public void getDoge(){<br>        PrintCoin printCoin = () -&gt; {<br>            coin = 50;<br>          <strong>  coinBought = new ArrayList(); //init reference inside lambda still remains local to lambda<br>            coinBought.add(80);<br>            coinBought.add(20); </strong><br>            coin += coinBought.stream().reduce(0, (coin1,coin2) -&gt; coin1+coin2);<br>            System.<em>out</em>.println(&quot;Doge to the MOoon! Bag it sis = &quot;+coin);<br>        };<br><br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br><br>        System.<em>out</em>.println(&quot;Doge value = &quot;+ doge.coin);<br>    }<br>}</pre><p>The reference has been initialized local to the lambda function.</p><p>If we try to access it elsewhere, it will throw an error as shown below</p><pre>package com.company;<br><br>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.List;<br><br>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    int coin;<br><br>    List&lt;Integer&gt; coinBought;<br><br>    public void getDoge(){<br>        PrintCoin printCoin = () -&gt; {<br>            coin = 50;<br>          <strong>  coinBought = new ArrayList(); //init is local to lambda function</strong><br>            coinBought.add(80);<br>            coinBought.add(20);<br>            coin += coinBought.stream().reduce(0, (coin1,coin2) -&gt; coin1+coin2);<br>            System.<em>out</em>.println(&quot;Doge to the MOoon! Bag it sis = &quot;+coin);<br>        };<br><br>       <strong> coinBought.add(30); //ERROR</strong><br>        printCoin.print();<br>    }<br><br>    public static void main(String []args){<br>        Doge doge = new Doge();<br>        doge.getDoge();<br><br>        System.<em>out</em>.println(&quot;Doge value = &quot;+ doge.coin);<br>    }<br>}</pre><p>Output,</p><pre>Exception in thread &quot;main&quot; java.lang.NullPointerException<br> at com.company.Doge.getDoge(Main.java:28)<br> at com.company.Doge.main(Main.java:34)</pre><p>Why does this occur? because the initialization done is local to the method.</p><p>In conclusion,</p><blockquote><strong>Insatnce variables can be initialized/manipulated anywhere inside method</strong></blockquote><blockquote><strong>Instance variables can be initialized/manipulated inside anywhere Lambda functions</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mVwT18Z5AHdi5kkZ" /><figcaption>Pineapple flexing after learning Instance Variables in Lambdas</figcaption></figure><p>That’s all folks!</p><p>Play around more! Do Let me know if I missed any scenarios.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71b5cb81b61d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 8 — Static Variables and Lambdas]]></title>
            <link>https://codesnoob.medium.com/static-variables-and-lambdas-ee16c2a0211e?source=rss-ba9c1723bcd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee16c2a0211e</guid>
            <category><![CDATA[java-8-feature]]></category>
            <category><![CDATA[static]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Sreenidhi KV]]></dc:creator>
            <pubDate>Sun, 16 May 2021 14:42:40 GMT</pubDate>
            <atom:updated>2021-05-16T16:45:56.092Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s learn about how to play around with static variables in lambdas.</p><p>The following scenarios will be covered</p><ol><li>Lambda consumes a static variable initialized in a static method</li><li>Lambda consumes a static variable initialized in lambda</li><li>Lambda functions with parameters and Static Variable</li><li>Static Reference Variable with Lambdas</li></ol><h3>Static Variable With Lambdas</h3><p>Let’s take the case where a variable is being consumed by Lambda</p><p>Let’s take a class (<strong><em>Doge</em></strong>) that consumes a Functional Interface (<strong><em>PrintCoin</em></strong>) which prints the number of coins.</p><p>The Functional Interface look like this, which takes a single abstract method <strong><em>print()</em></strong></p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}</pre><p>The Class <strong><em>Doge</em></strong> looks like this, we define the function as</p><p><strong><em>() -&gt; System.out.println(“I bought “ + coin +” Doge Coins”);</em></strong></p><p>which gets mapped to <strong><em>print()</em></strong></p><pre>class Doge{<br><br>    static int <em>coin</em>;</pre><pre>    public static void main(String []args){<br><br>        PrintCoin obj = () -&gt; System.<em>out</em>.println(&quot;I bought &quot; + <em>coin </em>+&quot; Doge Coins&quot;);<br>        obj.print();<br>    }<br>}</pre><p>The output will look like this</p><pre>I bought 0 Doge Coins</pre><p>Super simple! The lambda just consumes the static value.</p><p>The default value of coin is 0. Let’s initialize the values.</p><p>Voila! It just gets super easy from here!</p><h3>Initialize static variable in Static method</h3><p>Let’s initialize coin value to 100 (Doge to the MOoOooon!)</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    static int <em>coin</em>;<br><br>    public static void main(String []args){<br><br>      <strong>  <em>coin </em>= 100; //init in the static method</strong><br>        PrintCoin obj = () -&gt; System.<em>out</em>.println(&quot;I bought &quot; + <em>coin </em>+&quot; Doge Coins WooHoo!&quot;);<br>        obj.print();<br>    }<br>}</pre><p>Output Looks like this,</p><pre>I bought 100 Doge Coins WooHoo!</pre><p>Super Easy, all we had to do was initialize in the method. Just like any java program.</p><h3>Initialize static variable in Lambda function</h3><p>Can we change static variables inside Lambdas? <strong><em>HELL YES!</em></strong></p><p>Let’s start with changing the value in the lambda,</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    static int <em>coin</em>;<br><br>    public static void main(String []args){<br><br>    <strong><em>    coin = 100;</em></strong><br>        <br>        PrintCoin obj = () -&gt; {<br>           <strong><em> coin = coin + 20; //can manipulate static variables</em></strong><br>            System.<em>out</em>.println(&quot;I bought &quot; + <em>coin </em>+&quot; Doge Coins WooHoo!&quot;);<br>        };<br>        obj.print();<br><br>        System.<em>out</em>.println(&quot;I know that&#39;s right! &quot;+ <em>coin </em>+ &quot; Doge in my bag gurl!&quot;);<br>    }<br>}</pre><p>Output looks like</p><pre>I bought 120 Doge Coins WooHoo!<br>I know that&#39;s right! 120 Doge in my bag gurl!</pre><p>I know the initialization has occurred inside the static method in the above example, so let’s change it within the lambda,</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print();<br>}<br><br>class Doge{<br><br>    static int <em>coin</em>;<br><br>    public static void main(String []args){<br>        <br>        PrintCoin obj = () -&gt; {<br>          <strong>  <em>coin </em>= <em>coin </em>+ 20; //init in lambda </strong><br>            System.<em>out</em>.println(&quot;I bought &quot; + <em>coin </em>+&quot; Doge Coins WooHoo!&quot;);<br>        };<br>        obj.print();<br><br>        System.<em>out</em>.println(&quot;I know that&#39;s right! &quot;+ <em>coin </em>+ &quot; Doge in my bag gurl!&quot;);<br>    }<br>}</pre><p>Output? You already know the answer. It looks like this,</p><pre>I bought 20 Doge Coins WooHoo!<br>I know that&#39;s right! 20 Doge in my bag gurl!</pre><h3>Lambda with parameters</h3><p>The Functional Interface has an additional parameter in its method,</p><p><strong><em>print(int value)</em></strong></p><p>Works just like the previous, but just has parameters</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>   <strong> void print(int value); //parameter added</strong><br>}<br><br>class Doge{<br><br>    static int <em>coin</em>;<br><br>    public static void main(String []args){<br><br>        PrintCoin obj = <strong>value -&gt;</strong> {  <strong>//value present as parameter</strong><br>            value = value + 100;<br>            <em>coin </em>= <em>coin </em>+ 20 + value;<br>            System.<em>out</em>.println(&quot;I bought &quot; + <em>coin </em>+&quot; Doge Coins WooHoo!&quot;);<br>        };<br>       <strong> obj.print(500); //passing default value</strong><br><br>        System.<em>out</em>.println(<em>coin </em>+ &quot; coins!! Keep winning sis!&quot;);<br>    }<br>}</pre><p>Output,</p><pre>I bought 620 Doge Coins WooHoo!<br>620 coins!! Keep winning sis!</pre><h3>Static Reference Variable with Lambdas</h3><p>We will add a List of Integers that define the coins bought</p><p>Then we will add the total coins bought.</p><pre>@FunctionalInterface<br>interface PrintCoin{<br>    void print(int value);<br>}<br><br>class Doge{<br><br>    static int <em>coin</em>;<br><br>  <strong>  static List&lt;Integer&gt; <em>coinsBought </em>= Arrays.<em>asList</em>(20,50,50);</strong><br><br>    public static void main(String []args){<br><br>        PrintCoin obj = value -&gt; {<br>            value = value + 100;<br>         <strong>   <em>coin </em>= <em>coinsBought</em>.stream().reduce(0,(coin1,coin2) -&gt; coin1 + coin2 ); //total of coins bought, a simple sum of list</strong><br>            <em>coin </em>= <em>coin </em>+ value;<br>            System.<em>out</em>.println(&quot;I bought &quot; + <em>coin </em>+&quot; Doge Coins WooHoo!&quot;);<br>        };<br>        obj.print(500);<br><br>        System.<em>out</em>.println(<em>coin </em>+ &quot; coins!! Keep winning sis!&quot;);<br>    }<br>}</pre><p>Output,</p><pre>I bought 720 Doge Coins WooHoo!<br>720 coins!! Keep winning sis!</pre><p>It’s that Easy!</p><p>Static can be used as is, in Lambdas, like we did before java 8.</p><p>In short, here is the checklist of how static variables can be used,</p><blockquote>- Static variables can be accessed/manipulated anywhere within static methods</blockquote><blockquote>- Static variables can be accessed/manipulated anywhere in lambda functions</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9sQpIyy7DqmEJEXz" /><figcaption>Pineapple flexing after learning Static Variables in Lambdas</figcaption></figure><p>That’s all folks!</p><p>Play around more! Do Let me know if I missed any scenarios.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee16c2a0211e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>