<?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 Bindu Shrestha on Medium]]></title>
        <description><![CDATA[Stories by Bindu Shrestha on Medium]]></description>
        <link>https://medium.com/@bindushrestha?source=rss-5eeb5a381125------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gpj0iL-Ynee4eIYvOpOaeg@2x.jpeg</url>
            <title>Stories by Bindu Shrestha on Medium</title>
            <link>https://medium.com/@bindushrestha?source=rss-5eeb5a381125------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 10:27:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bindushrestha/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[Git commands to undo changes]]></title>
            <link>https://bindushrestha.medium.com/git-commands-to-undo-changes-58fd7a068367?source=rss-5eeb5a381125------2</link>
            <guid isPermaLink="false">https://medium.com/p/58fd7a068367</guid>
            <category><![CDATA[git-revert-to-last-commit]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-reset]]></category>
            <dc:creator><![CDATA[Bindu Shrestha]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 11:13:33 GMT</pubDate>
            <atom:updated>2023-06-19T11:13:33.876Z</atom:updated>
            <content:encoded><![CDATA[<p>Here I’ll be describing two git commands that I use commonly to undo or revert my changes.</p><ol><li><strong>git reset</strong></li></ol><p>Let’s say you made following three commits on your branch and you realized you don’t need last two commits. You could use git reset to go back to your first commit.</p><p>Get the list of your commits using git log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBbBjBf7A3j0f1WXeOf7QA.png" /></figure><p>If you’re pretty sure that you don’t need second and third commit at all. You can just do<strong> git reset — hard</strong> as seen below. You are back to first commit, second and third commit are completely gone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*znHZI94cgArhayL5x5003w.png" /></figure><p>If you do git log, you can find that the most recent commit is commit 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*cHpBM3zXvqCA9HLXSes-zA.png" /></figure><p>You can also reset last commit like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*BpGODEvjnLKXbVGfpYNMtA.png" /></figure><p>If you were to do HEAD~2, it would reset last two commit.</p><p>Let’s see what happens when I do <strong>git reset — soft.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*guOUa-o-g3JawKaWIg25jw.png" /></figure><p>As you can see second commit and third commit are undone. But this will preserve your changes in those two commits.</p><p>You can use git status command to find that the changes are present in your working area and staged. You can now decide to modify something and make a new commit or throw away changes using git reset — hard.</p><p>2. <strong>git revert</strong></p><p>git revert can be useful when you want to remove change from a commit but you want to preserve the commit history. This is useful if your changes are already pushed to remote repository and other teammates have those changes.</p><p>Do git log to see past commits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxj9Ok1CBqowzrVyWuW_Ng.png" /></figure><p>I would like to revert feature 2 as below. I got conflict since I made commits to the same file after feature 2 commit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kaJh5SO6bdGSI9IZhC32NQ.png" /></figure><p>Once you resolve the conflict you can do git revert — continue, to proceed with the revert. While reverting you will get this message, you can just do :wq to save the revert message and quite the editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlhn1cP5M0KIrTKow5r4Ww.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58fd7a068367" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 most used git commands]]></title>
            <link>https://bindushrestha.medium.com/top-10-most-used-git-commands-9c606d08f4c0?source=rss-5eeb5a381125------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c606d08f4c0</guid>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Bindu Shrestha]]></dc:creator>
            <pubDate>Sat, 15 Oct 2022 12:10:56 GMT</pubDate>
            <atom:updated>2022-10-15T12:10:56.910Z</atom:updated>
            <content:encoded><![CDATA[<p>Following is the list of git commands that are used most frequently.</p><ol><li><strong>git clone- </strong>Used to clone or copy existing repository. If you joined a new project today, this is the first command you’re going to use to create a local copy of the target repository. <br><strong>Ex:</strong> git clone<a href="https://github.com/bindushrestha/comparator-sample.git">https://github.com/bindushrestha/comparator-sample.git</a><br>Clone from remote repository.<br>git clone<a href="https://github.com/bindushrestha/comparator-sample.git">https://github.com/bindushrestha/comparator-sample.git</a> dir1<br>Clone to directory ‘dir1’.</li><li><strong>git init- </strong>Used to create a new git repository. If you create a new project this is the first command to run to turn it into a git project before you can run any other git command. <br><strong>Ex: </strong>git init<br>The git init command creates a new Git repository.</li><li><strong>git branch</strong>- Used to list, create or delete branches.<br><strong>Ex</strong>: git branch -a <br>List all the branches.<br>git branch -d feature1 <br>Delete branch called feature.<br>git branch -D feature1<br>Force delete branch feature1.<br>git branch feature2<br>Create new branch feature2.</li><li><strong>git checkout</strong>- Used to switch branch, switch to a older commit, copy file, undo changes in a file.<br><strong>Ex</strong>: git checkout feature2<br>Switch to branch feature2.<br>git checkout feature1 -- a.txt<br>Copy the file a.txt from feature1 branch to current branch.<br>git checkout 4cb52c9e9744854<br>Switch to a previous commit with the given commit id.</li><li><strong>git add- </strong>Used to add the changes made on current branch to staging area (can be thought of as a buffer, before the changes are actually saved to the repository). Files must be in staging area before they are actually saved using git commit. <br><strong>Ex: </strong>git add -a<br>Adds <strong>all </strong>the modified files to the staging area.<br>git add modifiedFile.txt<br>Adds <strong>modifiedFile.txt</strong> to staging area.<br><strong>Note</strong>: You will always use ‘git add’ with ‘git status’ and ‘git commit’.</li><li><strong>git status- </strong>Used to see the status of working directory. Let’s you see which files are staged for commit, which are not and which files aren’t being tracked by git on the current working branch.<br><strong>Ex:</strong> git status</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ptTWP4DiYCX8JIUzEWkVpQ.png" /><figcaption>git status example</figcaption></figure><p>In above example a.txt is added to staging area withgit add a.txtand can be committed. b.txt is modified but not added to staging, when committing this won’t be saved to the repository. c.txt is a new file which is not tracked yet by git. You can also dogit add c.txtto add this new file to staging area and git will start tracking it.</p><p>7. <strong>git commit-</strong> Used to save the currently staged changes to the local repository. The changes are committed to the branch you are currently working on. Commits are snapshots of the entire repository at a specific point in time. It’s a good idea to always include commit message when making a commit so that when you check the history you know exactly what changes were made in a particular commit.<br><strong>Ex:</strong> git commit -m “Add login feature”</p><p>8. <strong>git push-</strong> Used to transfer local commits to remote repository. After you make commits locally, you can share them with the remote repository using git push.<br><strong>Ex:</strong>git push<br>Push the changes on current branch to corresponding branch on remote.<br>When pushing new branch you can use the following:<br>git push -u origin feature1<br>Creates new ‘feature1&#39; branch in remote repository with tracking, so that from next push you can only usegit push .</p><p>9. <strong>git pull</strong>- Used to update the current branch with the changes in remote branch.<br><strong>Ex:</strong>git pull origin feature1 <br>Updates the currently checked out branch with the changes in the remote branch feature1.</p><p>If you do not mention any branch while doing git pull , it will update the the current branch and other remote tracking branches.</p><p>10. <strong>git stash </strong>— Used to save uncommitted changes. If you are in the middle of something, not yet ready to commit , you are going to need to save the task at hand before switching to something different. Git stash saves both staged and unstaged changes and reverts to the last commit. <br>Ex: git stash saves the changes in current branch.<br>git stash apply apply the saved changes to current branch.<br>git stash pop apply the saved changes to current branch and remove the stash.<br>git stash save &quot;Add mail service&quot; stash with message, useful in case you need to stash multiple times, to identify which stash you want to apply later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c606d08f4c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to resolve CORS error?]]></title>
            <link>https://bindushrestha.medium.com/why-do-you-get-cors-error-and-how-to-resolve-it-205ed0bed256?source=rss-5eeb5a381125------2</link>
            <guid isPermaLink="false">https://medium.com/p/205ed0bed256</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[cors]]></category>
            <dc:creator><![CDATA[Bindu Shrestha]]></dc:creator>
            <pubDate>Thu, 04 Aug 2022 14:07:20 GMT</pubDate>
            <atom:updated>2022-10-15T16:15:06.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*fFXQdFSyTAjJOGJJ.png" /></figure><p>If you have been developing REST APIs that are consumed by front end applications, it’s likely that you’ve come across this error, which is annoying for both frontend and backend developers. So let’s start with why we get this error? It’s because browsers don’t allow application from an origin to access resources on a different origin. This means that if your client application has a different domain or port than your backend, bowser will restrict the access to the resources on the backend.</p><p><strong>Same-origin policy (SOP)</strong></p><p>The Same-origin policy is developed as a security mechanism for browsers; which allows resource sharing only on same origin. For two websites to have the same origins, the websites should have the same domain, port number, and protocol type. If any one of the three properties is found differently, then the sources are considered different origins.</p><p><strong>Cross Origin Resource Sharing (CORS)</strong></p><p>Lets see, how we can let the browser know that the front end application is allowed to access the resources on our backend. CORS is a protocol that makes it possible. Cross Origin Resource Sharing (CORS) mechanism uses <strong>HTTP-headers </strong>to indicate that resource can be shared between cross origin. <strong>Browser makes a preflight (OPTIONS) request to the server to make sure that it will permit the actual request.</strong></p><p><strong>Preflight Request Headers</strong></p><p>A preflight request contains headers that indicates the origin, method type and headers the <strong>actual request </strong>will contain.</p><pre>OPTIONS /doc HTTP/1.1 Host: abc.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Connection: keep-alive Origin: <a href="https://foo.example/">https://foo.example</a> Access-Control-Request-Method: POST Access-Control-Request-Headers: Authorization, Content-Type</pre><ul><li>Origin: The Origin request header indicates the <a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">origin</a> (scheme, hostname, and port) that <em>caused</em> the request.</li><li>Access-Control-Request-Method: This header is used by the client to let the server know which <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods">HTTP method</a> will be used when the actual request is made.</li><li>Access-Control-Request-Headers: This header is used by the client to let the server know which <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers">HTTP headers</a> the client might send when the actual request is made.</li></ul><p><strong>Preflight Response Headers</strong></p><p>Once the server receives this request it is the responsibility of server to determine whether or not to permit the request. If the server permits the request from this <strong>origin </strong>it must add following headers to the response of preflight response.</p><ul><li>Access-Control-Allow-Origin — The whitelisted origin, or ‘*’</li><li>Access-Control-Allow-Methods — A comma-separated list of HTTP methods the web server wishes to permit for cross-origin requests</li><li>Access-Control-Allow-Headers — A comma-separated list of HTTP headers the web server wishes to permit for cross-origin requests</li></ul><p>There are other headers that can be added:</p><ul><li>Access-Control-Allow-Credentials-Server allows cookies (or other user credentials) to be included on cross-origin requests.</li><li>Access-Control-Max-Age- Indicates how long the result of preflight request can be cached.</li></ul><pre>Access-Control-Allow-Credentials: true<br>Access-Control-Allow-Headers: Authorization,Content-Type<br>Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS, DELETE<br>Access-Control-Allow-Origin: <a href="https://foo.example/">https://foo.example</a><br>Access-Control-Max-Age: 3600<br>Content-Length: 0</pre><p><strong>Response in Actual Request</strong></p><p>With these headers browser can determine if server permits actual request. Server must also add <strong>Access-Control-Allow-Origin</strong> to the response of actual request.</p><p>When credentials are passed with the request to the cross-origin server, the browser will not allow access to the response unless the cross-origin server sends a CORS header Access-Control-Allow-Credentials with a value of true.</p><p><strong>Sample filter that add CORS header</strong></p><pre>public class CorsFilter extends OncePerRequestFilter {<br><br>  @Value(&quot;${hosts}&quot;)<br>   private Set&lt;String&gt; allowDomains;<br><br>  @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,<br>      FilterChain filterChain) throws ServletException, IOException {<br>    String originHeader = request.getHeader(HttpHeaders.<em>ORIGIN</em>);<br>    if (allowDomains.contains(originHeader)) {<br>      response.setHeader(&quot;Access-Control-Allow-Origin&quot;, originHeader);<br>      response.setHeader(&quot;Access-Control-Allow-Credentials&quot;, &quot;true&quot;);<br>      if (HttpMethod.<em>OPTIONS</em>.name().equalsIgnoreCase(request.getMethod())) {<br>        response.setHeader(&quot;Access-Control-Allow-Methods&quot;, &quot;POST, PUT, GET, OPTIONS, DELETE&quot;);<br>        response.setHeader(&quot;Access-Control-Max-Age&quot;, &quot;3600&quot;);<br>        response.setHeader(&quot;Access-Control-Allow-Headers&quot;, &quot;Authorization,Content-Type&quot;);<br>        response.setStatus(HttpServletResponse.<em>SC_OK</em>);<br>      } else {<br>        filterChain.doFilter(request, response);<br>      }<br>    } else {<br>      filterChain.doFilter(request, response);<br>    }<br>  }<br>}</pre><p>Refrences: <br>https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS<br>https://reflectoring.io/complete-guide-to-cors/</p><p><em>Originally published at </em><a href="https://www.thecodecity.com/uncategorized/why-do-you-get-cors-error-and-how-to-resolve-it/"><em>https://www.thecodecity.com</em></a><em> on August 4, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=205ed0bed256" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to sort list of objects using multiple fields?]]></title>
            <link>https://bindushrestha.medium.com/how-to-order-list-of-objects-using-multiple-fields-b0b67c610613?source=rss-5eeb5a381125------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0b67c610613</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[sort]]></category>
            <category><![CDATA[comparator]]></category>
            <dc:creator><![CDATA[Bindu Shrestha]]></dc:creator>
            <pubDate>Tue, 10 May 2022 17:14:56 GMT</pubDate>
            <atom:updated>2022-05-10T17:31:18.294Z</atom:updated>
            <content:encoded><![CDATA[<p>We can sort list using multiple fields with Comparator. Here we are going to see two ways to do that.</p><p>Let’s say we have a Student class as below.</p><pre>public class Student {</pre><pre>private int rollNum;</pre><pre>private String firstName;</pre><pre>private String stream;</pre><pre>public Student(int rollNum, String firstName, String stream) {</pre><pre>super();</pre><pre>this.rollNum = rollNum;</pre><pre>this.firstName = firstName;</pre><pre>this.stream = stream;</pre><pre>}</pre><pre>public String getFirstName() {</pre><pre>return firstName;</pre><pre>}</pre><pre>public void setFirstName(String firstName) {</pre><pre>this.firstName = firstName;</pre><pre>}</pre><pre>public int getRollNum() {</pre><pre>return rollNum;</pre><pre>}</pre><pre>public void setRollNum(int rollNum) {</pre><pre>this.rollNum = rollNum;</pre><pre>}</pre><pre>public String getStream() {</pre><pre>return stream;</pre><pre>}</pre><pre>public void setStream(String stream) {</pre><pre>this.stream = stream;</pre><pre>}</pre><pre>@Override</pre><pre>public String toString() {</pre><pre>return stream +&quot; &quot; +firstName +&quot; &quot;+ rollNum;</pre><pre>}</pre><pre>}</pre><p>And a list of Students.</p><pre>private List&lt;Student&gt; getStudentList() {</pre><pre>return Arrays.asList(new Student(1, &quot;Bindu&quot;, &quot;IT&quot;), <br>new Student(2, &quot;Sam&quot;, &quot;CS&quot;), <br>new Student(3, &quot;David&quot;, &quot;IT&quot;),<br>new Student(4, &quot;Anjali&quot;, &quot;CS&quot;));}</pre><p>We can compare the list using multiple fields using two methods as below:</p><ol><li><strong>Anonymous Class</strong></li></ol><p>We can to make use of compare method in Comparator interface to compare using multiple fields. Comparator is a functional interface, which mean it has only one abstract method compare. We are going to override this method in anonymous class.</p><pre>private List&lt;Student&gt; sortWithAnymClass(List&lt;Student&gt; list) {</pre><pre>Collections.sort(list, new Comparator&lt;Student&gt;() {</pre><pre>// compare using stream and then rollNumber;</pre><pre>@Override</pre><pre>public int compare(Student s1, Student s2) {</pre><pre>if (s1.getStream().equals(s2.getStream())) {</pre><pre>if (s1.getRollNum() == s2.getRollNum())</pre><pre>return 0;</pre><pre>if (s1.getRollNum() &gt; s2.getRollNum())</pre><pre>return 1;</pre><pre>return -1;</pre><pre>}</pre><pre>return s1.getStream().compareTo(s2.getStream());</pre><pre>}</pre><pre>});</pre><pre>return list;</pre><pre>}</pre><p><strong>2. Using lambda expression</strong></p><pre>private List&lt;Student&gt; sortWithLambdaExp(List&lt;Student&gt; list) {</pre><pre>// sort using stream and firstName</pre><pre>list.sort(Comparator.comparing((Student s) -&gt; s.getStream()).thenComparing((Student s) -&gt; s.getFirstName()));</pre><pre>return list;</pre><pre>}</pre><p><em>Originally published at </em><a href="https://www.thecodecity.com/uncategorized/how-to-order-list-of-objects-using-multiple-fields/"><em>https://www.thecodecity.com</em></a><em> on May 10, 2022.</em></p><p><a href="https://github.com/bindushrestha/comparator-sample">https://github.com/bindushrestha/comparator-sample</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0b67c610613" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streams in Java — Quick Guide with Examples]]></title>
            <link>https://bindushrestha.medium.com/streams-in-java-quick-guide-with-examples-b52527de2c0b?source=rss-5eeb5a381125------2</link>
            <guid isPermaLink="false">https://medium.com/p/b52527de2c0b</guid>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Bindu Shrestha]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 15:21:07 GMT</pubDate>
            <atom:updated>2022-03-21T16:55:41.963Z</atom:updated>
            <content:encoded><![CDATA[<h3>Streams in Java — Quick Guide with Examples</h3><p>Java introduced <strong>Stream API</strong> in Java 8, which is useful to perform operations on collections. <strong>Java streams</strong> have definitely made processing collections and life easier. But in order to work with streams, it’s important to understand the following:</p><ol><li>Functional programming</li><li>Functional Interface</li><li>Lambda Expression</li></ol><p>Here I am going to explain all three concepts to help you understand Java Streams briefly.</p><h3>Underlying Concepts</h3><p>1. <strong>Functional Programming</strong>: Let’s start with functional programming, it’s a way of programming that is declarative, which means we write what we want instead of how to achieve that. Let’s take a simple example where we want to filter a list to get a list of strings starting with ‘J’. This is what our code would look like before streams. This is called imperative programming as we write the logic for what we want.</p><pre>List&lt;String&gt; list = new ArrayList&lt;String&gt;(Arrays.asList(&quot;Java&quot;,&quot;Java Script&quot;,&quot;C&quot;,&quot;Python&quot;)); <br>List&lt;String&gt; filteredList = new ArrayList&lt;String&gt;(); <br>for(String s:list) { <br>if(s.startsWith(&quot;J&quot;)) <br>{ filteredList.add(s); } <br>}</pre><p>This was lot compared to functional way, where we just make use of existing functions to achieve the same result. As can be seen below, it’s more declarative as we only state what we want which in our case is filter and collect, and our code is pretty concise.</p><pre>List&lt;String&gt; filteredList1 = list.stream().filter(s&gt;s.startWith(&quot;J&quot;)) <br>.collect(Collectors.toList());</pre><p>2. <strong>Functional Interfaces</strong>: A functional interface is an interface which have exactly one abstract method. Runnable is a functional interface as it contains only one abstract method run(). Let’s declare a functional interface as below which have single abstract method sayHello(). You might want to take a look at the functional interfaces introduced in java 8 like Predicate, Function, Consumer, Supplier.</p><pre>public MyInterface{<br> void sayHello(); <br>}</pre><p>3. <strong>Lambda Expression</strong>: A lambda expression is an unnamed method. It is used to implement a functional interface as it contains only one method. Here’s how to define lambda expression:</p><pre>(parameter list) -&gt; lambda body //body can have block {}</pre><p>-&gt; is known as lambda operator or arrow operator. we can implement <strong>MyInterface</strong> using lambda expression as below:</p><pre>()-&gt;System.out.println(&quot;Hello World!&quot;); <br>or<br>MyInterface mi = ()-&gt;System.out.println(&quot;Hello World!&quot;);</pre><p><strong>Lambda expression can be assigned to a variable or passed as a method argument.</strong></p><h3>Getting Into Java Streams</h3><p>Now that we have a basic idea of what functional programming, functional interface and lambda expressions are, let’s take a look in detail how these are used with streams. In our example of stream above we have used <strong>lambda expression</strong> as the argument for filter().</p><p>If we take a look at the signature of filter method, it takes <strong>Predicate </strong>as the method argument, which is a functional interface with an abstract method;<strong> boolean test(T t)</strong>. The implementation of this interface is the lambda expression<strong> s-&gt;s.startWith(“J”)</strong>, which we have passed to filter().</p><p>All the methods available in streams api makes operations on Collection simpler. The operations performed by these methods can be divided into<strong> intermediate and terminal</strong> operations. <strong>A new stream is produced after performing intermediate operation hence, multiple intermediate operations can be performed in pipeline, conversely, stream is said to be consumed after terminal operation and further operations cannot be performed.</strong></p><p>Examples of intermediate operations:</p><ol><li><strong>Filter</strong>: filter() is an intermediate operation and a new stream is produced after this operation.</li><li><strong>Map</strong>: map() is another very common intermediate operation, which takes <strong>Function </strong>as parameter.</li></ol><pre>List&lt;String&gt; listUpper = list.stream()<br>.map(s-&gt;s.toUpperCase()).collect(Collectors.toList());</pre><p>3. <strong>Sorted</strong>: sorted() is used for sorting and takes <strong>Comparator </strong>as parameter.</p><pre>List&lt;String&gt; sortedList = list.stream().sorted((s1,s2)-&gt; s1.compareTo(s2)).collect(Collectors.toList());</pre><p>Example of <strong>multiple intermediate operations</strong> map() and limit() in pipeline.</p><pre>List&lt;String&gt; limitedList = list.stream().map(s-&gt;s.toUpperCase()) .limit(3).collect(Collectors.toList());</pre><p>There are multiple other intermediate operations like disctinct(), flatMap() for which descriptions can be found in Stream API official documentation.</p><p>Examples of terminal operations:</p><pre>String langs = list.stream()<br>.filter(s-&gt;s.startsWith(&quot;J&quot;)).collect(Collectors.joining(&quot;,&quot;));</pre><p>2. <strong>Count</strong>: count() is used to count total number of elements in stream.</p><pre>long count = list.stream().filter(s-&gt;s.startsWith(&quot;J&quot;)).count();</pre><p>3. <strong>AnyMatch</strong>: anyMatch() takes a predicate as parameter and return boolean.</p><pre>boolean match = list.stream().anyMatch(x-&gt;x.equals(&quot;Java&quot;));</pre><p>4. <strong>Reduce</strong>: reduce() takes BinaryOperator to reduce the stream. Stream API contains set of predefined reduction operations such as average (), sum (), min (), max (), and count ().</p><pre>Optional&lt;String&gt; reduced = list.stream().reduce((a,b)-&gt;a+&quot;,&quot;+b);<br>or<br>String reduced = list.stream().reduce(&quot;&quot;,(a,b)-&gt;a+&quot;,&quot;+b); //reduce with initial value returns String not Optional</pre><p><strong>Lazy Evaluation</strong>: One of the most important characteristics of Java streams is that they allow for significant optimizations through lazy evaluations. <strong>All intermediate operations are lazy, so they’re not executed until a result of a processing is required.</strong> You would note in the following example that peek only prints first element starting with ‘J’ which is ‘Java’ and wouldn’t filter other elements.</p><pre>Optional&lt;String&gt; first = list.stream().filter(s-&gt;s.startsWith(&quot;J&quot;)) .peek(s1-&gt;System.out.println(&quot;Peeking :&quot;+s1)).findFirst();</pre><p><strong>Note</strong>: It would be excellent to go through the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html">official documentation</a> of Stream API to see the exhaustive list of available methods.</p><p><strong>Find the sample code</strong>: <a href="https://github.com/bindushrestha/stream-examples">https://github.com/bindushrestha/stream-examples</a></p><p><em>Originally published at </em><a href="https://www.thecodecity.com/java/streams-in-java/"><em>https://www.thecodecity.com</em></a><em> on March 20, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b52527de2c0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inheritance and Object Casting in Java]]></title>
            <link>https://bindushrestha.medium.com/inheritance-and-object-casting-in-java-2cb926ae0d29?source=rss-5eeb5a381125------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cb926ae0d29</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[inheritance]]></category>
            <dc:creator><![CDATA[Bindu Shrestha]]></dc:creator>
            <pubDate>Fri, 28 Jan 2022 09:58:06 GMT</pubDate>
            <atom:updated>2022-01-28T09:58:06.349Z</atom:updated>
            <content:encoded><![CDATA[<p>Inheritance is an important concept of OOP. It allows inheriting fields and methods using ‘extends’ keyword. With inheritance, we can create a class with basic features and behaviors and create its specialized versions, by creating classes, that inherit this base class. The base class is also called superclass or parent class and the class that inherits from the base class is called subclass or child class. As we can see, inheritance facilitates the reusability of code by allowing the use of existing fields and methods.</p><p>For example, we can have an Employee class that has fields like name and employeeId as we can safely assume all employees have these. We can then go ahead and create class Programmer that have a specialized field like technology, as seen in the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*Fgi2a0gfyMKlgeGrWdkkQg.png" /><figcaption>Base class Employee</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*gWwaYt8DlJd1_NFvc6ceJw.png" /><figcaption>Programmer, subclass of Employee</figcaption></figure><p><strong>Note</strong>: printEmployeeDesc() in Programmer overrides method printEmployeeDesc in superclass Employee.</p><p><strong>IS-A relationship</strong></p><p>We use inheritance when there’s is-a relationship, in our example, we used inheritance since we know that a programmer is an employee. As every class directly or indirectly inherits from Object, it is also an Object. Therefore in the example above, a Programmer is an Employee and an Object.</p><p>Casting shows the use of an object of one type in place of another.<strong> Since the reference variable only refers to an object but doesn’t contain the object itself, casting does not change the actual object but only labels an object in another way, expanding or narrowing opportunities to work with it.</strong> Upcasting narrows the list of methods and properties available to the object, and downcasting can extend it.</p><p><strong>Upcasting:</strong></p><p>Object obj = new Programmer(“Irene”,”1002&quot;,”Php”);</p><p>Employee emp = new Programmer(“Ian”,”1003&quot;,”Php”);</p><p><strong>Casting from a subclass to a superclass is called upcasting.</strong> Typically, the upcasting is implicitly performed by the compiler.<strong> </strong>As can be seen from the example, in upcasting a reference variable is assigned to a more specific type. Programmer has access to the members of Employee and Object so upcasting is usually safe.</p><p><strong>Downcasting:</strong></p><p>Programmer programmer = (Programmer) obj;</p><p>Programmer programmer = (Programmer) emp;</p><p><strong>Casting from a superclass to a subclass is called downcasting. </strong>Unlike upcasting, downcasting can fail if the actual object type is not the target object type. For example:</p><p>Employee emp = new Employee(“Sita”,”1005&quot;);</p><p>Programmer programmer = (Programmer) emp;</p><p>This will throw a ClassCastException during run-time because the actual object type of emp is Employee and an Employee is not a Programmer.</p><p><strong>Example of object casting:</strong></p><p>Continuing with our example we might want to have a method to print descriptions of employees. We could then use this method to print descriptions of different employees like Programmer or BA, and it would print descriptions specific to type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*JMDiecpDOA-gY89Bjygokg.png" /><figcaption>Print description of specific type of employee</figcaption></figure><p>Points to be noted from the example:</p><ol><li>When calling printEmpDesc(programmer) from main method, Programmer is implicitly cast to Employee.</li><li>The method that actually gets executed during runtime is of Programmer as the actual object is of type Programmer. So the output will be as seen below:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*pxf979P1nwFbgZrvsWavaQ.png" /><figcaption>Output on console</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cb926ae0d29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exceptions in Java]]></title>
            <link>https://bindushrestha.medium.com/exceptions-in-java-c95cebd19047?source=rss-5eeb5a381125------2</link>
            <guid isPermaLink="false">https://medium.com/p/c95cebd19047</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[exception]]></category>
            <dc:creator><![CDATA[Bindu Shrestha]]></dc:creator>
            <pubDate>Sat, 02 Oct 2021 19:51:05 GMT</pubDate>
            <atom:updated>2021-10-02T19:51:05.581Z</atom:updated>
            <content:encoded><![CDATA[<p>The term <em>exception</em> is shorthand for the phrase “exceptional event.”</p><p><strong>Definition:</strong> An <em>exception</em> is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.</p><p>When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an <em>exception object</em>, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called <em>throwing an exception</em>.</p><p>I got this definition from the java documentation. I’m not sure how clear you are with the definition so I’ll do a bit of explaining here:</p><p>Let’s say we want string array to store courses available for CS students.</p><p>String[] courses ={“Web Development&quot;, &quot;Electronic Communication”, “Microprocessors”};</p><p>And somewhere else in the program we try to access element at index 5.</p><p>System.out.println(courses[5]);</p><p>Since our array only contains 3 elements what should happen? Java has a way of handling this ‘exceptional event’; in a perfect world we should have never tried to access index that’s not there. But since we did and there’s no element at index 5, java creates an object of type ArrayIndexOutOfBoundsException and hands it to runtime system, in the world of java it’s called throwing an exception.</p><p>The exception object contains information related to the event as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*dwKpsSZlM65PJoqmkQSa9A.png" /></figure><p>First line tells the type of exception followed by description. Second line tells where this exception occurred, at line 14 in Example.java.</p><p>As we can see from the example, normal flow of the program should be to print the array element at given index. But since we try to print element which is not present, its an error and it disrupts the normal flow of program. Java handles it by throwing an exception object and terminates execution at the line exception occurred.</p><p>And since now we know what happened in our program we can go ahead and fix that..</p><p>In java there’s hierarchy of classes that represents different kind of events that can disrupt normal program flow. Below we will discuss the types of exceptions.</p><p>Exception hierarchy in java:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*7Mn_R6SMyjXVuqAE.jpg" /></figure><p>The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of the Object class. Throwable has two direct subclasses — Exception and Error.</p><p>Error: These represent errors that occurs outside our program. For example if jvm runs out of memory, it throws OutOfMemory error and terminates. These occur during run time and application cannot recover from these.</p><p>Unchecked Exception(run-time): All sub classes of RunTimeException are unchecked exceptions. ArrayIndexOutOfBoundsException is a type of run time exception. These error can be avoided by the programmers as can be seen in above example.</p><p>Checked Exceptions(compile-time): These represents the kind of errors that should be anticipated and handled in code. All subclasses of Exception besides RuntimeException are checked exceptions. These are called checked exceptions since compiler checks if these are handled in the code. Compiler forces to handles these exception and gives error if not handled. Let’s take an example of checked exception.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*Fxhi8ncOCotUj-W_Ei6tdQ.png" /></figure><p>If you check the implementation of readLine() method in BufferedReader class you can see that it throws IOException. It’s compile time exception and needs to be handled in the try catch block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*uVbB_HYQ_geUCBYLYplfBg.png" /></figure><p>In our example since we have handled IOException in the try catch block, program does not terminate where the exception occurs. Instead it will execute the catch block and continue executing following lines. As can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*jOBSE_NOvGh6UsnX-3R6pA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c95cebd19047" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Creation in Java]]></title>
            <link>https://bindushrestha.medium.com/object-creation-in-java-51bd0b113bdc?source=rss-5eeb5a381125------2</link>
            <guid isPermaLink="false">https://medium.com/p/51bd0b113bdc</guid>
            <dc:creator><![CDATA[Bindu Shrestha]]></dc:creator>
            <pubDate>Sat, 18 Sep 2021 15:36:41 GMT</pubDate>
            <atom:updated>2021-09-18T15:36:41.130Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*SDIMdogVXJjxhaVgC2aP7w.png" /></figure><p>Classes and objects are the fundamentals in java. Having a good understanding of how objects are created is essential for object oriented programming.</p><p><strong>new Operator</strong></p><p><strong>new </strong>is a keyword in java that is used to create new object as the name suggests. What it does is allocate memory for the new object and returns a reference to it. So when we say object is created, that basically means memory is allocated for the object.</p><p>Let’s take a example of a Cat class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*3J43isfDLB9IogGZ3hj0MA.png" /></figure><p>Cat mimi = new Cat();</p><p>In the above line, when java sees the variable mimi, it allocates memory for it and this memory is going to store reference to Cat object. It’s only when it sees the <strong>new </strong>keyword it allocates the memory for the Cat object in a section called heap, which would have space for our variable ‘<strong>name</strong>’ and ‘<strong>color</strong>’ in Cat class. Also note that creating an object is same as creating an instance of the class hence it’s also called instantiating a class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*1-lePnwU4_q0xFJfUbuCCQ.jpeg" /></figure><p>When instantiating a class, new keyword is followed by constructor, which is same as init() method in other languages used to initialize variables in the class. If we do not pass any parameter to the constructor, instance variables are assigned default values as in our case.</p><p>There are some interesting points to note about constructor:<br>1. If our class does not have any constructor, compiler will add a constructor with no parameter called default constructor. So in our Cat class above, compiler will add a default constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*7YmjX9nVfnMpvPGka1E2tA.png" /></figure><p>2. If our class extends from any other class, first line in the constructor must be call to parent class constructor or constructor of same class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*_CpsTnOx6wkOtf_Pnt4Kig.png" /></figure><p>This means that when creating objects, initialization happens from the inside out. When we call the Cat() constructor the first line super() will call the Animal() constructor, and Object() constructor will be called in turn. So the first constructor to be executed is of the Object class, the call returns to the Animal constructor which gets executed and finally the Cat constructor will be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*gd4485wvuBhfOCV-sDMR0g.png" /></figure><p>Calling constructor of same class or parent class after any other lines of code will give compile time error. Following will give compile time error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*RZsTs1jlNBzNa-aNGkZv0g.png" /></figure><p>3. Another important point is that every class in java directly or indirectly inherits from Object class. Compiler add this code automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*aAF-vG3xkGW5p2MHrEYW-A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51bd0b113bdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>