{"id":1111,"date":"2020-11-12T11:47:49","date_gmt":"2020-11-12T11:47:49","guid":{"rendered":"https:\/\/blog.samarthya.me\/wps\/?p=1111"},"modified":"2020-11-12T11:47:52","modified_gmt":"2020-11-12T11:47:52","slug":"java-streams","status":"publish","type":"post","link":"https:\/\/blog.samarthya.me\/wps\/2020\/11\/12\/java-streams\/","title":{"rendered":"Java Streams"},"content":{"rendered":"\n<p><em>Stream<\/em> is an new abstraction that lets one process data in a declarative way.<\/p>\n\n\n\n<figure class=\"wp-block-pullquote is-style-solid-color\"><blockquote><p><strong>A stream does not store data and, in that sense, is not a data structure. It also never modifies the underlying data source.<\/strong><\/p><\/blockquote><\/figure>\n\n\n\n<p>The easiest way to learn a new API or a construct is by trying it. So here is an <a href=\"https:\/\/github.com\/samarthya\/javaex\/tree\/local\/grains\" data-type=\"URL\" data-id=\"https:\/\/github.com\/samarthya\/javaex\/tree\/local\/grains\">exercise<\/a> that I tried to learn the Stream API. This is an exercise from <a href=\"https:\/\/exercism.io\/my\/solutions\/428fcd2c497c4098b5bd3121a1d66110\">exercism.io<\/a>. <\/p>\n\n\n\n<p>The problem is the famous <code>grains <\/code>problem doubling the number of grains on each square of the chess which has 64 squares (8&#215;8).<\/p>\n\n\n\n<p>I started of by keeping things simple having a <code>LinkedHashMap<\/code> that stores <code>pre-initalized<\/code> square and number of <code>grains<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>private Map&lt;Integer, BigInteger> lHM = new LinkedHashMap&lt;>();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>private void Initialize() {\n        for(int i=0; i&lt;64; i++) {\n            if (i == 0) {\n                lHM.put(Integer.valueOf(1), BigInteger.ONE);\n                continue;\n            }\n            lHM.put(i+1, lHM.get(i).multiply(BigInteger.TWO));\n        }\n    }<\/code><\/pre>\n\n\n\n<p><code>lHM<\/code> defined is initalized for all the possible grain permutations for a 64 square board.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>lHM.put(i+1, lHM.get(i).multiply(BigInteger.TWO));<\/code><\/pre>\n\n\n\n<p>E.g. <\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>For every square > 1 we are putting <code>Grains in the previous square * 2<\/code><\/li><\/ul>\n\n\n\n<p>This is very simple version of and had to be improved so time to use Streams.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.math.BigInteger;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\nimport java.util.stream.IntStream;\n\n\/**\n * Grains on a board.\n * 1 + 2 + 6 + 18 + .......\n *\/\nclass Grains {\n\n    BigInteger grainsOnSquare(final int square) {\n        if (square &lt; 1 || square > 64) {\n            throw new IllegalArgumentException(\"square must be between 1 and 64\");\n        }\n       return BigInteger.TWO.pow(square - 1);\n    }\n\n    BigInteger grainsOnBoard() {\n        return IntStream.range(1, 65).mapToObj( i -> grainsOnSquare(i)).reduce(BigInteger::add).get();\n    }\n\n}<\/code><\/pre>\n\n\n\n<p>I did away with the data-structure and resorted to use simple Streams &#8211; <code><a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/stream\/IntStream.html\" data-type=\"URL\" data-id=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/stream\/IntStream.html\">IntStream<\/a><\/code>.<\/p>\n\n\n\n<p>For the method <\/p>\n\n\n\n<pre id=\"block-70101b39-0f28-4726-9c83-3e9a01d24ccb\" class=\"wp-block-code\"><code>grainsOnSquare<\/code><\/pre>\n\n\n\n<p>I have used <code>pow<\/code> method of <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/math\/BigInteger.html\" data-type=\"URL\" data-id=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/math\/BigInteger.html\">BigInteger<\/a> which simple calculates 2^(Square &#8211; 1)<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>1st Square 2^0 = 1<\/li><li>2nd Square 2^1 = 2<\/li><li>&#8230;. 4th Square 2^3 = 8<\/li><\/ul>\n\n\n\n<p>Now it is easier to read and optimised. How about the total grains here is where the streams come in handy for me as I do not have a DS storing any values.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>IntStream.range(1, 65).mapToObj( i -> grainsOnSquare(i)).reduce(BigInteger::add).get();<\/code><\/pre>\n\n\n\n<p>I used the <code>range()<\/code> method to iterate between 1-64 as the second parameter is exclusive, and then for each square <code>i<\/code> I got the <code>grainsOnSquare<\/code> which was reduced using <code>BigInteger.add<\/code> and the final value is returned.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/stream\/Stream.html<\/li><li>https:\/\/www.oracle.com\/technical-resources\/articles\/java\/ma14-java-se-8-streams.html<\/li><li>https:\/\/docs.oracle.com\/javase\/tutorial\/collections\/intro\/index.html<\/li><\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Stream is an new abstraction that lets one process data in a declarative way. A stream does not store data and, in that sense, is not a data structure. It also never modifies the underlying data source. The easiest way to learn a new API or a construct is by trying it. So here is [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":1112,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"image","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"footnotes":""},"categories":[120,34],"tags":[121,122],"class_list":["post-1111","post","type-post","status-publish","format-image","has-post-thumbnail","hentry","category-java","category-technical","tag-java","tag-streams","post_format-post-format-image"],"_links":{"self":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/1111","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/comments?post=1111"}],"version-history":[{"count":0,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/1111\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media\/1112"}],"wp:attachment":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media?parent=1111"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/categories?post=1111"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/tags?post=1111"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}