{"id":4238,"date":"2021-05-03T13:17:36","date_gmt":"2021-05-03T13:17:36","guid":{"rendered":"https:\/\/codethataint.com\/blog\/?p=4238"},"modified":"2026-01-27T17:06:31","modified_gmt":"2026-01-27T17:06:31","slug":"code-snippets-for-stream","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/code-snippets-for-stream\/","title":{"rendered":"Streams &#8211; Filter, Map and Reduce"},"content":{"rendered":"<p> <strong class=\"ctaHeader2\">Streams<\/strong><\/p>\n<p>Stream is a Wrapper class around a data structure with some additional methods such as filter, map, reduce. When you create a stream out of array or list, copy of data in array exist as it is in stack. only wrapper is created around the reference of array or list. Converting an array to a stream doesn\u2019t copy data, it just wraps the array in a stream object for functional-style processing.<\/p>\n<p><em>The stream does not modify the original array. It\u2019s a read-only view. It wraps the existing array in a Spliterator.<br \/>\n<\/em>. The elements are not duplicated or moved. The stream just holds a reference to the array and knows how to iterate over it.<\/p>\n<p>A Spliterator in Java is a special type of iterator introduced in Java 8 that can both traverse and partition elements of a data source. It\u2019s designed to efficiently split data into chunks so multiple threads can process them concurrently<\/p>\n<p><strong>When not to use Streams?<\/strong><\/p>\n<p>When you create a stream, Java allocates a Stream pipeline object and a Spliterator wrapper around the source. These objects add overhead compared to a raw loop, but they enable functional-style operations and parallelism. Spliterator doesn\u2019t always split. In sequential streams, it just traverses. Splitting only happens when parallel streams are used, where trySplit() divides the source into chunks for concurrent processing.<\/p>\n<blockquote><p>Collection \u2192 Spliterator \u2192 Stream \u2192 Consumer<\/p><\/blockquote>\n<ol>\n<li>Create a Spliterator wrapper<\/li>\n<li>Create a Stream pipeline object<\/li>\n<li>Use Spliterator to walk the backing array and feed elements into the lambda consumer<\/li>\n<\/ol>\n<p>In for loop<\/p>\n<blockquote><p> Collection \u2192 Index\/Iterator \u2192 Consumer<\/p><\/blockquote>\n<p>The for loop skips the extra object creation (Stream + Spliterator wrappers) and directly feeds elements to the consumer, which is why it\u2019s faster and lighter for simple tasks.<\/p>\n<p><strong>What is Spliterator?<\/strong><\/p>\n<p>A Spliterator is a special type of iterator that is designed to traverse and partition elements of a data source. The name itself comes from \u201cSplit + Iterator\u201d.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codethataint.com\/blog\/wp-content\/uploads\/2021\/05\/streamsEg.png\" alt=\"\" \/><\/p>\n<ol>\n<li><strong>Intermediate Operations<\/strong> returns Stream as output. methods like map(), sorted(), distinct() would return stream as output<\/li>\n<li><strong>Terminal Operations<\/strong> returns something other than Stream. Collect() returns collection. Reduce() returns one element<\/li>\n<\/ol>\n<p><strong>Converting list to a stream and print them<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nList&lt;Integer&gt; arrNumbers = List.of(10,27,31, 35, 40, 44, 48, 50);\r\n\/\/Convert list to stream\r\nStream objStream = arrNumbers.stream();\r\n\r\n\/\/Static Method Reference\r\nobjStream.forEach(System.out::println);\r\n<\/pre>\n<blockquote><p>\n<strong>Both Map and Filter returns Streams.<br \/>\nFilter takes predicate as input and adds element to stream based on result of predicate(I.E. True or false).<br \/>\nMap takes function as input and adds transformed object value to stream.<br \/>\nReduce takes function as input and returns a single value that is computed going over the entire rows in stream.<\/strong>\n<\/p><\/blockquote>\n<p><strong class=\"ctaHeader2\">Filter<\/strong><br \/>\n<em>Filter is used for filtering the data, it always returns the boolean value. If it returns true, the item is added to list else it is filtered out (ignored)<\/em><\/p>\n<ol>\n<li>Filter takes a predicate as argument. Predicate returns boolean. The Output of Filter is a Stream<\/li>\n<li>Predicate object which is technically a function to convert an object to boolean. We pass an object and it will return true or false. <\/li>\n<li>filter() method is lazy like map, it wont be evaluated until you call a reduction method, like collect<\/li>\n<\/ol>\n<p><strong class=\"ctaHeader2\">Using Filter to filter names in list and print them<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nimport java.util.*;\r\nimport java.util.stream.Stream;\r\n\r\nList&lt;String&gt; arrNames = List.of(&quot;Mugil&quot;, &quot;Mani&quot;, &quot;Madhu&quot;);\r\narrNames.stream()\r\n        .filter(name -&gt; name.equals(&quot;Mugil&quot;))\r\n        .forEach(System.out::println);\r\n<\/pre>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nList&lt;Integer&gt; arrNumbers = List.of(10,27,31, 35, 40, 44, 48, 50);\r\nList&lt;String&gt; arrSkills = List.of(&quot;Spring Boot&quot;, &quot;Spring Security&quot;, &quot;Java 8&quot;, &quot;Microservices&quot;, &quot;Spring MVC&quot;);\r\n\r\n\/\/Printing Even Numbers\r\nSystem.out.println(&quot;------Even Numbers-------&quot;);\r\narrNumbers.stream().filter(FilterEgs::isEven).forEach(System.out::println);\r\n\r\n\/\/Printing Even Numbers\r\nSystem.out.println(&quot;------Even Numbers-------&quot;);\r\narrNumbers.stream().filter(no -&gt; no%2==0).forEach(System.out::println);\r\n\r\n\/\/Printing Odd Numbers\r\nSystem.out.println(&quot;------Odd Numbers-------&quot;);\r\narrNumbers.stream().filter(no -&gt; no%2==1).forEach(System.out::println);\r\n\r\n\/\/Printing Odd Numbers\r\nSystem.out.println(&quot;------Print Spring Skills-------&quot;);\r\narrSkills.stream().filter(skill -&gt; skill.toLowerCase().contains(&quot;spring&quot;))\r\n.forEach(System.out::println);\r\n\r\nprivate static boolean isEven(int no){\r\n        return no%2==0;\r\n}       \r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\n------Even Numbers-------\r\n10\r\n40\r\n44\r\n48\r\n50\r\n------Odd Numbers-------\r\n27\r\n31\r\n35\r\n------Print Spring  Skills-------\r\nSpring Boot\r\nSpring Security\r\nSpring MVC\r\n<\/pre>\n<p><strong class=\"ctaHeader2\">Map<\/strong><br \/>\n<em>By using map, you transform the object values. the map returns the transformed object value as Stream.<\/em><\/p>\n<ol>\n<li>Map takes a function as a argument and performs transform action on elements. The Output of Map is a Stream<\/li>\n<li>map() is used to transform one object into another by applying a function.<\/li>\n<li>Stream.map(Function mapper) takes a function as an argument.<\/li>\n<li>mapping function converts one object to the other. Then, the map() function will do the transformation for you. It is also an intermediate Stream operation, which means you can call other Stream methods, like a filter, or collect on this to create a chain of transformations.<\/li>\n<\/ol>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nList&lt;Integer&gt; arrNum = List.of(5,6,8,57,4,1,26,84,15);\r\nList&lt;String&gt; arrSkills = List.of(&quot;Spring Boot&quot;, &quot;Spring Security&quot;, &quot;Java 8&quot;, &quot;Microservices&quot;, &quot;Spring MVC&quot;);\r\n\r\n\r\n\/\/Printing Square of Numbers whose value less than 15\r\nSystem.out.println(&quot;------Square of Numbers-------&quot;);\r\narrNum.stream()\r\n      .filter(num -&gt; num&lt;15)   \r\n      .map(num -&gt; num*num)\r\n      .forEach(System.out::println);\r\n\r\n\r\n\/\/Print Total Characters in String\r\nSystem.out.println(&quot;------Print Total Characters in String-------&quot;);\r\narrSkills.stream()\r\n\t\t.map(skill -&gt; skill + &quot; contains &quot;+ skill.length()+ &quot; Characters&quot;)\r\n\t\t.forEach(System.out::println);\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\n------Square of Numbers-------\r\n25\r\n36\r\n64\r\n16\r\n1\r\n------Print Total Characters in String-------\r\nSpring Boot Contains 11 Characters\r\nSpring Security Contains 4 Characters\r\nJava 8 Contains 5 Characters\r\n<\/pre>\n<p><strong class=\"ctaHeader2\">Reduce<\/strong><\/p>\n<ol>\n<li>Stream.reduce() takes function as Parameter<\/li>\n<li>Reduction stream operations allow us to produce one single result from a sequence of elements, by repeatedly applying a combining operation to the elements in the sequence.<\/li>\n<li>Stream.reduce() operation Contains Identity, Accumulator and Combiner<\/li>\n<li><strong>Identity <\/strong>\u2013 an element that is the initial value of the reduction operation and the default result if the stream is empty<\/li>\n<li><strong>Accumulator <\/strong>\u2013 a function that takes two parameters: a partial result of the reduction operation and the next element of the stream<\/li>\n<li><strong>Combiner<\/strong> \u2013 a function used to combine the partial result of the reduction operation when the reduction is parallelized or when there&#8217;s a mismatch between the types of the accumulator arguments and the types of the accumulator implementation\n<\/li>\n<li><\/li>\n<\/ol>\n<p><strong>ReduceEgs.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nimport java.util.Arrays;\r\nimport java.util.List;\r\n\r\npublic class ReduceEgs {\r\n    public static void main(String&#x5B;] args) {\r\n        List&lt;Integer&gt; arrNumbers =  Arrays.asList(1,2,3,4,5,6,7,8,9);\r\n\r\n        System.out.println(arrNumbers.stream().reduce(0, ReduceEgs::sumNos));\r\n    }\r\n\r\n    public static Integer sumNos(int x, int y){\r\n        System.out.println(&quot;a -&quot;+ x + &quot; b - &quot;+  y);\r\n\r\n        return x+y;\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\na -0 b - 1\r\na -1 b - 2\r\na -3 b - 3\r\na -6 b - 4\r\na -10 b - 5\r\na -15 b - 6\r\na -21 b - 7\r\na -28 b - 8\r\na -36 b - 9\r\n45\r\n<\/pre>\n<p>In the above example<\/p>\n<ol>\n<li>the Integer value 0 is the <em><strong>identity<\/strong><\/em>. It stores the initial value of the reduction operation and also the default result when the stream of Integer values is empty.<\/li>\n<li>the lambda expression x+y represented by function sumNos is the <em><strong>accumulator<\/strong><\/em> since it takes the partial sum of Integer values and the next element in the stream.<\/li>\n<li>When a stream executes in parallel, the Java runtime splits the stream into multiple substreams. In such cases, we need to use a function to combine the results of the substreams into a single one. This is the role of the <em><strong>combiner<\/strong><\/em><\/li>\n<\/ol>\n<p>Role of combiner would be visibile only in parallelStream with output as below. It would be hard to interpret the output response in console.<\/p>\n<p><strong>ReduceEgs.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n.\r\n.\r\n System.out.println(arrNumbers.parallelStream().reduce(0, ReduceEgs::sumNos));\r\n.\r\n.\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\na -0 b - 6\r\na -0 b - 5\r\na -5 b - 6\r\na -0 b - 1\r\na -0 b - 7\r\na -0 b - 9\r\na -0 b - 2\r\na -1 b - 2\r\na -0 b - 3\r\na -0 b - 8\r\na -8 b - 9\r\na -0 b - 4\r\na -3 b - 4\r\na -3 b - 7\r\na -7 b - 17\r\na -11 b - 24\r\na -10 b - 35\r\n45\r\n<\/pre>\n<p><strong>Alternate ways to Sum Nos <\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic static void main(String&#x5B;] args) {\r\n List&lt;Integer&gt; arrNumbers =  Arrays.asList(1,2,3,4,5,6,7,8,9);\r\n\r\n Integer sum = arrNumbers.stream().reduce(0, Integer::sum);\r\n Integer sum2 = arrNumbers.stream().reduce(0, (x,y)-&gt;x+y);\r\n\r\n System.out.println(sum);\r\n System.out.println(sum2);\r\n}\r\n<\/pre>\n<p>Once you get the values in stream then it should be typecast to its original type before calling its methods as values are stored as Objects in stream<\/p>\n<p>Below you could see the name is typecast to String before calling lowerCase method<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nList&lt;String&gt; arrNames = Arrays.asList(&quot;Mugil&quot;, &quot;Mani&quot;, &quot;Vinu&quot;);\r\nStream arrNameStream = arrNames.stream();\r\narrNameStream.forEach(name -&gt; System.out.println(((String)name).toLowerCase()));\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Streams Stream is a Wrapper class around a data structure with some additional methods such as filter, map, reduce. When you create a stream out of array or list, copy of data in array exist as it is in stack. only wrapper is created around the reference of array or list. Converting an array to&hellip; <a href=\"https:\/\/codethataint.com\/blog\/code-snippets-for-stream\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[251],"tags":[],"class_list":["post-4238","post","type-post","status-publish","format-standard","hentry","category-streams"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/4238","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=4238"}],"version-history":[{"count":6,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/4238\/revisions"}],"predecessor-version":[{"id":5736,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/4238\/revisions\/5736"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=4238"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=4238"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=4238"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}