{"id":15042745,"url":"https://github.com/alpha74/java_streams_guide","last_synced_at":"2026-01-30T07:13:13.300Z","repository":{"id":254731915,"uuid":"847384868","full_name":"alpha74/Java_streams_Guide","owner":"alpha74","description":"A shortguide to Java 8 streams on Collections","archived":false,"fork":false,"pushed_at":"2024-08-30T06:01:30.000Z","size":27,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-20T12:06:11.116Z","etag":null,"topics":["java","java-8","java-collections","java-stream","java-stream-api","java-stream-collector"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alpha74.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-08-25T17:12:57.000Z","updated_at":"2024-08-30T06:01:33.000Z","dependencies_parsed_at":"2024-08-29T13:28:16.810Z","dependency_job_id":null,"html_url":"https://github.com/alpha74/Java_streams_Guide","commit_stats":null,"previous_names":["alpha74/java_streams_guide"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alpha74%2FJava_streams_Guide","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alpha74%2FJava_streams_Guide/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alpha74%2FJava_streams_Guide/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alpha74%2FJava_streams_Guide/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alpha74","download_url":"https://codeload.github.com/alpha74/Java_streams_Guide/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243441836,"owners_count":20291543,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["java","java-8","java-collections","java-stream","java-stream-api","java-stream-collector"],"created_at":"2024-09-24T20:47:55.758Z","updated_at":"2026-01-30T07:13:13.263Z","avatar_url":"https://github.com/alpha74.png","language":null,"readme":"## Java streams() Guide\n\n- A guide to Java 8 streams on Collections\n\n-------\n\n### Overview \n\nA birds-eye view of all major methods based on `Collections` and `stream()`\n\n![image](https://github.com/user-attachments/assets/fa11c742-8bf6-46dd-adbc-04056b48485d)\n\n\n- [Youtube source](https://www.youtube.com/watch?v=33JrZGtKOEE\u0026list=PLUDwpEzHYYLvTPVqVIt7tlBohABLo4gyg\u0026index=1\u0026ab_channel=SDET-QA)\n\n- `Collections`\n        - It represents a a group of objects as a single entity.\n\n- `Stream`\n        - It is used to process data from collections.\n\n- `Non-terminal Operation`\n        - It is an operation which adds a listener to the stream which may modify the stream elements.\n\n- `Terminal Operation`\n        - It is an operations which returns a result after stream processing.\n\n\n-------\n\n\n#### filter()\n\n- Takes a `predicate` as a argument, which returns a `boolean` as output.\n\n- Example of filter() on a List of integers.\n\n```\nList\u003cInteger\u003e numbersList = Arrays.asList(10,15,20,25,30);\n```\n\n```\n// Create list of even numbers: using collect()\nList\u003cInteger\u003e evenList1 = numbersList.stream()\n        .filter(n -\u003e n % 2 == 0)\n        .collect(Collectors.toList());\n\n// Same: Create list of even numbers: using toList() shorthard\nList\u003cInteger\u003e evenList2 = numbersList.stream()\n        .filter(n -\u003e n % 2 == 0)\n        .toList();\n```\n\n- Takes a `consumer` expression as input and does not return anything.\n\n```\n// Print even numbers\nnumbersList.stream().filter(n -\u003e n % 2 == 0).forEach(n -\u003e System.out.println(n));\n\n// Same: Print even numbers using shorthand method reference\nnumbersList.stream().filter(n -\u003e n % 2 == 0).forEach(System.out::println);\n```\n\n- `System.out` is a static method.\n\n- Example of filter() on a List of strings.\n \n```\nList\u003cString\u003e stringList = List.of(\"OptimusPrime\", null, \"Megatron\", \"Bumblebee\", \"Ratchet\", null);\n\n// Filter non-null values which have len \u003e 7\nList\u003cString\u003e longStringList = stringList.stream().filter(s -\u003e s != null \u0026\u0026 s.length() \u003e 7).toList();\n```\n\n-------\n\n#### map()\n\n- It accepts a function or consumer as input.\n\n- Example for converting each string in a List to UpperCase\n\n```\nList\u003cString\u003e vehicles = List.of(\"car\", \"bus\", \"train\", \"place\", \"ship\");\n\n// Convert each item to upper case\nList\u003cString\u003e vehiclesUpperCase = vehicles.stream()\n      .map(name -\u003e name.toUpperCase())\n      .collect(Collectors.toList());\n```\n\n- Example for calculating len of each string and appending to same item\n\n```\n// Find length of each element and append to same item\nList\u003cString\u003e vehicleLenList = vehicles.stream()\n        .map(name -\u003e name + \" len is \" + name.length())\n        .collect(Collectors.toList());\n```\n\n-------\n\n#### flatMap()\n\n- Given a collection of objects, `map()` takes one input and returns one output, whereas `flatMap()` takes one input, but returns a stream of objects.\n\n- Example to combine a list of list of objects into single list using `flatMap()`\n\n```\nList\u003cInteger\u003e list1 = Arrays.asList(1,2);\nList\u003cInteger\u003e list2 = Arrays.asList(3,4);\nList\u003cInteger\u003e list3 = Arrays.asList(5,6);\n\nList\u003cList\u003cInteger\u003e\u003e listList = Arrays.asList(list1, list2, list3);\n\n// Combine all lists into single list\nList\u003cInteger\u003e combinedList = listList.stream().flatMap(x -\u003e x.stream()).collect(Collectors.toList());\n\n// Output: [1,2,3,4,5,6]\n```\n\n```\n// Operating on each item in each list and combining to single list\ncombinedList = listList.stream().flatMap(x -\u003e x.stream()).map(n -\u003e n +10).collect(Collectors.toList());\n```\n\n-------\n\n#### distinct()\n\n- Find distinct elements from a given collection.\n\n```\nList\u003cString\u003e vehicleList = Arrays.asList(\"car\", \"bike\", \"car\", \"bike\", \"truck\", \"ship\");\nList\u003cString\u003e uniqueVehicleList = vehicleList.stream().distinct().collect(Collectors.toList());\n```\n\n\n#### count() \u0026 limit()\n\n- `count()` returns count of objects as `long`.\n\n```\nList\u003cString\u003e vehicleList = Arrays.asList(\"car\", \"bike\", \"car\", \"bike\", \"truck\", \"ship\");\nlong count = vehicleList.stream().distinct().count();                // Returns 4\n```\n\n- `limt()` is used to collect a limited number of objects from a stream.\n- Takes `maxsize` as input param.\n\n```\nlong count = vehicleList.stream().distinct().limit(2).count();        // Returns 2\n```\n\n-------\n\n#### min() \u0026 max()\n\n- Takes a `comparator()` as input, and returns an `Optional\u003c\u003e` object.\n\n```\nList\u003cInteger\u003e numList = Arrays.asList(1,1,2,2,3,4);\n\nOptional\u003cInteger\u003e minVal = numList.stream().min((val1, val2) -\u003e {return val1.compareTo(val2);});\nSystem.out.println(minVal.get());   // 1\n\nOptional\u003cInteger\u003e maxVal = numList.stream().max((val1, val2) -\u003e {return val1.compareTo(val2);});\nSystem.out.println(maxVal.get());   // 4\n```\n\n-------\n\n#### reduce()\n\n- Takes input as an `identity` and `accumulator` as params.\n- Reduces all elements in the stream to a single object.\n\n```\nList\u003cInteger\u003e numList = Arrays.asList(1,1,2,2,3,4);\n\n// Calculate sum\nOptional\u003cInteger\u003e sumVal = numList.stream().reduce((val, combinedVal) -\u003e {\n            return val + combinedVal;\n        });\n\n\nList\u003cString\u003e vehicleList = Arrays.asList(\"car\", \"bike\", \"car\", \"bike\", \"truck\", \"ship\");\n\n// Append all strings to single string\nOptional\u003cString\u003e appended = vehicleList.stream().reduce((val, combined) -\u003e {\n    return val+combined;\n});\n```\n\n-------\n\n#### toArray()\n\n- It converts the stream of objects to array.\n\n```\nList\u003cInteger\u003e numList = Arrays.asList(1,1,2,2,3,4);\n\n// Convert to array\nObject arr[] = numList.stream().toArray();\n```\n\n-------\n\n#### sorted()\n\n- Used to sort a stream of objects.\n\n```\nList\u003cInteger\u003e numList = Arrays.asList(2,5,1,6,3,7);\n\n// Sort in ascending order\nList\u003cInteger\u003e ascSorted = numList.stream().sorted().collect(Collectors.toList());\n\n// Sort in descending order\nList\u003cInteger\u003e descSorted = numList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());\n```\n\n-------\n\n#### anyMatch() \n\n- Returns `true` if condition matches any value in the stream.\n\n```\nSet\u003cString\u003e fruits = new HashSet\u003c\u003e();\n\nfruits.add(\"21 mangoes\");\nfruits.add(\"31 apples\");\nfruits.add(\"412 oranges\");\nfruits.add(\"13 guavas\");\n\nboolean res1 = fruits.stream().anyMatch(val -\u003e {return val.contains(\"4\");});        // true\n```\n\n\n#### allMatch() \n\n- Returns `true` if all elements match the condition, else `false`.\n\n```\nboolean res2 = fruits.stream().allMatch(val -\u003e {return val.contains(\"1\");});        // true\n```\n\n#### noneMatch()\n\n- Returns `true` if none of the elements match the conditions, else `false`.\n\n```\nboolean res3 = fruits.stream().noneMatch(val -\u003e {return val.contains(\"s\");});        // false\n```\n\n-------\n\n#### findAny()\n\n- Returns `Optional\u003c\u003e`, or `NoSuchElementException` if no element is found.\n- It may or may not return the first matched element.\n\n```\nList\u003cInteger\u003e numList = Arrays.asList(2,5,1,6,3,7);\n\nOptional\u003cInteger\u003e any = numList.stream().findAny();        // 2 (but non-deterministic, helpful in parallelStream())\n```\n\n#### findFirst()\n\n- Returns `Optional\u003c\u003e`, or `NoSuchElementException` if no element is found.\n- It strictly returns the first matched element.\n\n```\nList\u003cInteger\u003e numList = Arrays.asList(2,5,1,6,3,7);\n\nOptional\u003cInteger\u003e first = numList.stream().findFirst();        // 2\n```\n\n\n-------\n\n##### Stream.concat()\n\n- Used to concatenate two `Stream` objects into single `Stream`.\n\n```\nList\u003cString\u003e list1 = Arrays.asList(\"dog\", \"cat\", \"rat\");\nList\u003cString\u003e list2 = Arrays.asList(\"eagle\", \"sparrow\", \"hen\");\n\nStream\u003cString\u003e stream1 = list1.stream();\nStream\u003cString\u003e stream2 = list2.stream();\n\nList\u003cString\u003e concatenated = Stream.concat(stream1, stream2).collect(Collectors.toList());\nSystem.out.println(concatenated);\n```\n\n\n-------\n\n#### Parallel Streams\n\n- All collections support `parallelStream()` method that returns a possibly parallel stream.\n- When a stream executes in parallel, the Java Runtime divides the stream into multiple substreams.\n- The aggregate operators iterates over these sub-streams in parallel and then combine the result. This can improve the performance.\n\n- Eg: `List\u003cString\u003e parallelStream = list1.parallelStream()`\n\n- Using `stream()`, operations are performed sequentially, but using `parallelStream()`, operations are performed parallely.\n\n```\nList\u003cString\u003e vehicleList = Arrays.asList(\"car\", \"bike\", \"car\", \"bike\", \"truck\", \"ship\");\n\n// Using stream()\nList\u003cString\u003e filterSeq = vehicleList.stream().filter(x -\u003e x.contains(\"a\")).collect(Collectors.toList());\n\n// Using parallelStream()\nList\u003cString\u003e filterPar = vehicleList.parallelStream().filter(x -\u003e x.contains(\"a\")).collect(Collectors.toList());\n\n// Convert stream to parallel stream\nList\u003cString\u003e filterPar2 = vehicleList.stream().parallel().filter(x -\u003e x.contains(\"a\")).collect(Collectors.toList());\n```\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falpha74%2Fjava_streams_guide","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falpha74%2Fjava_streams_guide","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falpha74%2Fjava_streams_guide/lists"}