├── .github
└── workflows
│ └── gradle.yml
├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
├── main
└── java
│ └── io
│ └── github
│ └── jhspetersson
│ └── packrat
│ ├── AtLeastGatherer.java
│ ├── AtMostGatherer.java
│ ├── BreakingGatherer.java
│ ├── CollectingGatherer.java
│ ├── DistinctByGatherer.java
│ ├── DropLastNGatherer.java
│ ├── DropNthGatherer.java
│ ├── EqualChunksGatherer.java
│ ├── FilterEntriesGatherer.java
│ ├── FilteringGatherer.java
│ ├── FilteringWithIndexGatherer.java
│ ├── FixedSizeDeque.java
│ ├── FlatMapGatherer.java
│ ├── IdentityGatherer.java
│ ├── IncreasingDecreasingChunksGatherer.java
│ ├── IncreasingDecreasingGatherer.java
│ ├── IntoListGatherer.java
│ ├── LastingGatherer.java
│ ├── MapWhileUntilGatherer.java
│ ├── MappingGatherer.java
│ ├── MinMaxGatherer.java
│ ├── NCopiesGatherer.java
│ ├── NthGatherer.java
│ ├── Packrat.java
│ ├── PeekWithIndexGatherer.java
│ ├── RemoveDuplicatesGatherer.java
│ ├── RepeatGatherer.java
│ ├── RotateLeftGatherer.java
│ ├── SamplingGatherer.java
│ ├── WindowFixedWithIndexGatherer.java
│ ├── WindowSlidingWithIndexGatherer.java
│ ├── ZipGatherer.java
│ ├── ZipWithIndexGatherer.java
│ └── package-info.java
└── test
└── java
└── io
└── github
└── jhspetersson
└── packrat
├── AtLeastTest.java
├── AtMostTest.java
├── BreakingTest.java
├── CollectingTest.java
├── DistinctByTest.java
├── DropLastNTest.java
├── DropNthGathererTest.java
├── Employee.java
├── EqualChunksGathererTest.java
├── FilterEntriesTest.java
├── FilterWithIndexTest.java
├── FilteringTest.java
├── FlatMapTest.java
├── IdentityGathererTest.java
├── IncreasingDecreasingChunksTest.java
├── IncreasingDecreasingTest.java
├── IntoListTest.java
├── LastNTest.java
├── MapWhileUntilTest.java
├── MapWithIndexTest.java
├── MappingTest.java
├── MinMaxTest.java
├── NCopiesTest.java
├── NthTest.java
├── PeekWithIndexTest.java
├── RemoveDuplicatesTest.java
├── RepeatGathererTest.java
├── SamplingTest.java
├── TestUtils.java
├── WindowFixedWithIndexTest.java
├── WindowSlidingWithIndexTest.java
├── ZipTest.java
└── ZipWithIndexTest.java
/.github/workflows/gradle.yml:
--------------------------------------------------------------------------------
1 | name: Java CI with Gradle
2 |
3 | on:
4 | push:
5 | branches: [ "master" ]
6 | workflow_dispatch:
7 |
8 | jobs:
9 | build:
10 | runs-on: ubuntu-latest
11 |
12 | steps:
13 | - name: Checkout sources
14 | uses: actions/checkout@v4
15 |
16 | - name: Set up JDK 24
17 | uses: actions/setup-java@v4
18 | with:
19 | java-version: '24'
20 | distribution: 'corretto'
21 |
22 | - name: Setup Gradle
23 | uses: gradle/actions/setup-gradle@v4
24 | with:
25 | gradle-version: '8.14'
26 |
27 | - name: Make gradlew executable
28 | run: chmod +x ./gradlew
29 |
30 | - name: Build with Gradle Wrapper
31 | run: ./gradlew build
32 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | .idea
3 | *.iml
4 | build/
5 | !**/src/main/**/build/
6 | !**/src/test/**/build/
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Packrat
2 |
3 | Packrat is a Java library that provides various [Gatherer](https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/util/stream/Gatherer.html) implementations for the Stream API. Gatherers can enhance streams with custom intermediate operations.
4 |
5 | [Introduction to the Gatherers by Viktor Klang](https://www.youtube.com/watch?v=8fMFa6OqlY8)
6 |
7 | ### Availability
8 |
9 | > [!IMPORTANT]
10 | > You will need a very fresh JDK version with preview features enabled to actually use Gatherers.
11 |
12 | |JEP|JDK|Status|
13 | |---|---|---|
14 | |[461](https://openjdk.org/jeps/461)|22|Preview|
15 | |[473](https://openjdk.org/jeps/473)|23|Second Preview|
16 | |[485](https://openjdk.org/jeps/485)|24|Final|
17 |
18 | Build scripts expect to run on JDK version not lower than 24.
19 |
20 | ### Usage
21 |
22 | #### Maven
23 |
24 | ```xml
25 |
26 | io.github.jhspetersson
27 | packrat
28 | 0.1.0
29 |
30 | ```
31 |
32 | #### Gradle
33 |
34 | ```groovy
35 | implementation("io.github.jhspetersson:packrat:0.1.0")
36 | ```
37 |
38 | ### Gatherers
39 |
40 | #### Filtering and mapping operations
41 |
42 | | Name | Description |
43 | |----------------------------------------------------------------|-----------------------------------------------------------------------------------|
44 | | [distinctBy](#distinctby) | Distinct values with custom mapper |
45 | | [filterBy](#filterby) | Filter with custom mapper and (optionally) predicate |
46 | | [filterEntries](#filterentries) | Filter Map.Entry elements using a BiPredicate on key and value |
47 | | [removeBy](#removeby) | Remove with custom mapper and (optionally) predicate |
48 | | [removeEntries](#removeentries) | Remove Map.Entry elements using a BiPredicate on key and value |
49 | | [removeDuplicates](#removeduplicates) | Removes consecutive duplicates from a stream |
50 | | [flatMapIf](#flatmapif) | Optional `flatMap` depending on predicate |
51 | | [minBy](#minby) | The smallest element compared after mapping applied |
52 | | [maxBy](#maxby) | The greatest element compared after mapping applied |
53 |
54 | #### Sequence operations
55 |
56 | | Name | Description |
57 | |----------------------------------------------------------------|-----------------------------------------------------------------------------------|
58 | | [increasing](#increasing) | Increasing sequence, other elements dropped |
59 | | [increasingOrEqual](#increasingorequal) | Increasing (or equal) sequence, other elements dropped |
60 | | [decreasing](#decreasing) | Decreasing sequence, other elements dropped |
61 | | [decreasingOrEqual](#decreasingorequal) | Decreasing (or equal) sequence, other elements dropped |
62 | | [reverse](#reverse) | All elements in reverse order |
63 | | [rotate](#rotate) | All elements rotated left or right |
64 | | [shuffle](#shuffle) | All elements in random order |
65 |
66 | #### Mapping with position operations
67 |
68 | | Name | Description |
69 | |----------------------------------------------------------------|-----------------------------------------------------------------------------------|
70 | | [mapFirst](#mapfirst) | Maps first element with mapper, other unchanged |
71 | | [mapN](#mapn) | Maps __n__ elements, other unchanged |
72 | | [skipAndMap](#skipandmap) | Skips __n__ elements, maps others |
73 | | [skipAndMapN](#skipandmapn) | Skips __skipN__ elements, maps __mapN__ others |
74 | | [mapWhile](#mapwhile) | Maps elements using the supplied function while the predicate evaluates to true. |
75 | | [mapUntil](#mapuntil) | Maps elements using the supplied function until the predicate evaluates to false. |
76 |
77 | #### Collection and chunking operations
78 |
79 | | Name | Description |
80 | |----------------------------------------------------------------|-----------------------------------------------------------------------------------|
81 | | [increasingChunks](#increasingchunks) | Lists of increasing values |
82 | | [increasingOrEqualChunks](#increasingorequalchunks) | Lists of increasing or equal values |
83 | | [equalChunks](#equalchunks) | Lists of equal values |
84 | | [decreasingChunks](#decreasingchunks) | Lists of decreasing values |
85 | | [decreasingOrEqualChunks](#decreasingorequalchunks) | Lists of decreasing or equal values |
86 | | [nCopies](#ncopies) | Copies every element __n__ times |
87 | | [repeat](#repeat) | Collects the whole stream and repeats it __n__ times |
88 | | [atLeast](#atleast) | Distinct values that appear at least __n__ times |
89 | | [atMost](#atmost) | Distinct values that appear at most __n__ times |
90 |
91 | #### Indexing and zipping operations
92 |
93 | | Name | Description |
94 | |----------------------------------------------------------------|-----------------------------------------------------------------------------------|
95 | | [zip](#zip) | Zips values with zipper, leftovers dropped |
96 | | [mapWithIndex](#zipwithindex) or [zipWithIndex](#zipwithindex) | Maps/zips values with an increasing index |
97 | | [peekWithIndex](#peekwithindex) | Peek at each element with its index |
98 | | [filterWithIndex](#filterwithindex) | Filter elements based on their index and a predicate |
99 | | [removeWithIndex](#removewithindex) | Remove elements based on their index and a predicate |
100 | | [windowSlidingWithIndex](#windowslidingwithindex) | Returns fixed-size windows of elements along with their indices |
101 | | [windowFixedWithIndex](#windowfixedwithindex) | Returns fixed-size non-overlapping windows of elements along with their indices |
102 |
103 | #### Element selection operations
104 |
105 | | Name | Description |
106 | |----------------------------------------------------------------|-----------------------------------------------------------------------------------|
107 | | [sample](#sample) | Sample of the specified size |
108 | | [nth](#nth) | Takes nth element from the stream |
109 | | [dropNth](#dropnth) | Drops every nth element from the stream |
110 | | [last](#last) | Last __n__ elements |
111 | | [lastUnique](#lastunique) | Last __n__ unique elements |
112 | | [dropLast](#droplast) | Drops last __n__ elements |
113 |
114 | #### Text processing operations
115 |
116 | | Name | Description |
117 | |----------------------------------------------------------------|-----------------------------------------------------------------------------------|
118 | | [chars](#chars) | String split by Unicode graphemes |
119 | | [words](#words) | String split by words |
120 | | [sentences](#sentences) | String split by sentences |
121 |
122 | #### Utility operations
123 |
124 | | Name | Description |
125 | |----------------------------------------------------------------|-----------------------------------------------------------------------------------|
126 | | [asGatherer](#asgatherer) | Converts `Collector` into `Gatherer` |
127 | | [identity](#identity) | Passes elements through unchanged |
128 |
129 | ### Filtering and mapping operations
130 |
131 | #### distinctBy
132 |
133 | `distinctBy(mapper)` - returns elements with distinct values that result from a mapping by the supplied function
134 |
135 | ```java
136 | import static io.github.jhspetersson.packrat.Packrat.distinctBy;
137 | var oneOddOneEven = IntStream.range(1, 10).boxed().gather(distinctBy(i -> i % 2)).toList();
138 | System.out.println(oneOddOneEven);
139 | ```
140 | > [1, 2]
141 |
142 | #### filterBy
143 |
144 | `filterBy(mapper, value)` - filters mapped elements based on the equality to the value, stream continues with original elements
145 |
146 | ```java
147 | import static io.github.jhspetersson.packrat.Packrat.filterBy;
148 | var oneDigitNumbers = IntStream.range(0, 100).boxed().gather(filterBy(i -> i.toString().length(), 1)).toList();
149 | System.out.println(oneDigitNumbers);
150 | ```
151 | > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
152 |
153 | `filterBy(mapper, value, predicate)` - filters mapped elements based on the predicate test against the value, stream continues with original elements
154 |
155 | ```java
156 | import static io.github.jhspetersson.packrat.Packrat.filterBy;
157 | var ffValue = IntStream.range(0, 1000).boxed().gather(filterBy(Integer::toHexString, "ff", String::equalsIgnoreCase)).toList();
158 | System.out.println(ffValue);
159 | ```
160 | > [255]
161 |
162 | #### filterEntries
163 |
164 | `filterEntries(predicate)` - filters Map.Entry elements using a BiPredicate that tests the key and value of each entry
165 |
166 | ```java
167 | import static io.github.jhspetersson.packrat.Packrat.filterEntries;
168 | var map = Map.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
169 |
170 | // Filter entries where the value is even
171 | var evenValues = map.entrySet().stream()
172 | .gather(filterEntries((key, value) -> value % 2 == 0))
173 | .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
174 | System.out.println(evenValues);
175 | ```
176 | > {two=2, four=4}
177 |
178 | #### removeBy
179 |
180 | `removeBy(mapper, value)` - removes mapped elements based on the equality to the value, stream continues with original elements
181 |
182 | ```java
183 | import static io.github.jhspetersson.packrat.Packrat.removeBy;
184 | var oneDigitNumbers = IntStream.range(0, 100).boxed().gather(removeBy(i -> i.toString().length(), 2)).toList();
185 | System.out.println(oneDigitNumbers);
186 | ```
187 | > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
188 |
189 | `removeBy(mapper, value, predicate)` - removes mapped elements based on the predicate test against the value, stream continues with original elements
190 |
191 | ```java
192 | import static io.github.jhspetersson.packrat.Packrat.removeBy;
193 | var ageDivisibleByThree = getEmployees().gather(removeBy(emp -> emp.age() % 3, 0, (i, value) -> !Objects.equals(i, value))).toList();
194 | System.out.println(ageDivisibleByThree);
195 | ```
196 | > [Employee[name=Mark Bloom, age=21], Employee[name=Rebecca Schneider, age=24]]
197 |
198 | #### removeEntries
199 |
200 | `removeEntries(predicate)` - removes Map.Entry elements using a BiPredicate that tests the key and value of each entry
201 |
202 | ```java
203 | import static io.github.jhspetersson.packrat.Packrat.removeEntries;
204 | var map = Map.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
205 |
206 | // Remove entries where the value is even
207 | var oddValues = map.entrySet().stream()
208 | .gather(removeEntries((key, value) -> value % 2 == 0))
209 | .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
210 | System.out.println(oddValues);
211 | ```
212 | > {one=1, three=3, five=5}
213 |
214 | #### removeDuplicates
215 |
216 | `removeDuplicates()` - removes consecutive duplicates from a stream, only adjacent elements that are equal will be considered duplicates
217 |
218 | ```java
219 | import static io.github.jhspetersson.packrat.Packrat.removeDuplicates;
220 | var listWithCopies = List.of(0, 1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8, 9, 8, 7, 7, 6, 5, 4, 4, 4, 3, 2, 1, 0);
221 | var unique = listWithCopies.stream().gather(removeDuplicates()).toList();
222 | System.out.println(unique);
223 | ```
224 | > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
225 |
226 | #### removeDuplicatesBy
227 |
228 | `removeDuplicatesBy(mapper)` - removes consecutive duplicates from a stream based on a mapping function, only adjacent elements that have equal mapped values will be considered duplicates
229 |
230 | ```java
231 | import static io.github.jhspetersson.packrat.Packrat.removeDuplicatesBy;
232 | var people = List.of(
233 | new Person("John", 25),
234 | new Person("Alice", 30),
235 | new Person("Bob", 30),
236 | new Person("Charlie", 30),
237 | new Person("David", 40),
238 | new Person("Eve", 40)
239 | );
240 | var uniqueByAge = people.stream().gather(removeDuplicatesBy(Person::age)).toList();
241 | System.out.println(uniqueByAge);
242 | ```
243 | > [Person[name=John, age=25], Person[name=Alice, age=30], Person[name=David, age=40]]
244 |
245 | #### flatMapIf
246 |
247 | `flatMapIf(mapper, predicate)` - optionally flattens elements mapped to streams depending on the supplied predicate
248 |
249 | ```java
250 | import static io.github.jhspetersson.packrat.Packrat.flatMapIf;
251 | var strings = Stream.of("A", "BC", "DEF");
252 | var result = strings.gather(flatMapIf(s -> Arrays.stream(s.split("")), s -> s.length() >= 3)).toList();
253 | System.out.println(result);
254 | ```
255 |
256 | > [A, BC, D, E, F]
257 |
258 | #### minBy
259 |
260 | `minBy(mapper)` - returns the smallest element in the stream, comparing is done after mapping function applied.
261 |
262 | ```java
263 | import static io.github.jhspetersson.packrat.Packrat.minBy;
264 | var check = Stream.of("2", "1", "-12", "22", "10").gather(minBy(Long::parseLong)).toList();
265 | System.out.println(check);
266 | ```
267 |
268 | > [-12]
269 |
270 | However, resulting list contains an original element of type `String`;
271 |
272 | `minBy(mapper, comparator)` - returns the smallest element in the stream, comparing with given comparator is done after mapping function applied.
273 |
274 | > [!CAUTION]
275 | > This gatherer will consume the entire stream before producing any output.
276 |
277 | #### maxBy
278 |
279 | `maxBy(mapper)` - returns the greatest element in the stream, comparing is done after mapping function applied.
280 |
281 | ```java
282 | import static io.github.jhspetersson.packrat.Packrat.maxBy;
283 | var check = Stream.of("2", "1", "-12", "22", "10").gather(maxBy(Long::parseLong)).toList();
284 | System.out.println(check);
285 | ```
286 |
287 | > [22]
288 |
289 | However, resulting list contains an original element of type `String`;
290 |
291 | `maxBy(mapper, comparator)` - returns the greatest element in the stream, comparing with given comparator is done after mapping function applied.
292 |
293 | > [!CAUTION]
294 | > This gatherer will consume the entire stream before producing any output.
295 |
296 | ### Sequence operations
297 |
298 | #### increasing
299 |
300 | `increasing()` - returns elements in an increasing sequence, elements out of the sequence, as well as repeating values, are dropped
301 |
302 | ```java
303 | import static io.github.jhspetersson.packrat.Packrat.increasing;
304 | var numbers = Stream.of(1, 2, 2, 5, 4, 2, 6, 9, 3, 11, 0, 1, 20);
305 | var increasingNumbers = numbers.gather(increasing()).toList();
306 | System.out.println(increasingNumbers);
307 | ```
308 |
309 | > [1, 2, 5, 6, 9, 11, 20]
310 |
311 | #### increasingOrEqual
312 |
313 | `increasingOrEqual()` - returns elements in an increasing sequence, repeating values are preserved, elements out of the sequence are dropped
314 |
315 | #### decreasing
316 |
317 | `decreasing()` - returns elements in a decreasing sequence, elements out of the sequence, as well as repeating values, are dropped
318 |
319 | #### decreasingOrEqual
320 |
321 | `decreasingOrEqual()` - returns elements in a decreasing sequence, repeating values are preserved, elements out of the sequence are dropped
322 |
323 | #### reverse
324 |
325 | `reverse()` - reverses the elements
326 |
327 | ```java
328 | import static io.github.jhspetersson.packrat.Packrat.reverse;
329 | var reverseOrdered = IntStream.range(0, 10).boxed().gather(reverse()).toList();
330 | System.out.println(reverseOrdered);
331 | ```
332 | > [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
333 |
334 | > [!CAUTION]
335 | > This gatherer will consume the entire stream before producing any output.
336 |
337 | #### rotate
338 |
339 | `rotate(distance)` - rotates the elements
340 |
341 | ```java
342 | import static io.github.jhspetersson.packrat.Packrat.rotate;
343 | var positiveRotation = IntStream.range(0, 10).boxed().gather(rotate(3)).toList();
344 | System.out.println(positiveRotation);
345 | var negativeRotation = IntStream.range(0, 10).boxed().gather(rotate(-4)).toList();
346 | System.out.println(negativeRotation);
347 | ```
348 | > [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]
349 |
350 | > [4, 5, 6, 7, 8, 9, 0, 1, 2, 3]
351 |
352 | > [!CAUTION]
353 | > This gatherer will consume the entire stream before producing any output.
354 |
355 | #### shuffle
356 |
357 | `shuffle()` - shuffle the elements
358 |
359 | ```java
360 | import static io.github.jhspetersson.packrat.Packrat.shuffle;
361 | var randomlyOrdered = IntStream.range(0, 10).boxed().gather(shuffle()).toList();
362 | System.out.println(randomlyOrdered);
363 | ```
364 | > [2, 7, 6, 9, 8, 5, 1, 3, 0, 4]
365 |
366 | > [!CAUTION]
367 | > This gatherer will consume the entire stream before producing any output.
368 |
369 | ### Mapping with position operations
370 |
371 | #### mapFirst
372 |
373 | `mapFirst(mapper)` - returns all elements, the first element is mapped with the supplied mapping function
374 |
375 | ```java
376 | import static io.github.jhspetersson.packrat.Packrat.mapFirst;
377 | var mapped = IntStream.rangeClosed(1, 10).boxed().gather(mapFirst(n -> n * 10)).toList();
378 | System.out.println(mapped);
379 | ```
380 |
381 | > [10, 2, 3, 4, 5, 6, 7, 8, 9, 10]
382 |
383 | #### mapN
384 |
385 | `mapN(n, mapper)` - returns all elements, the first __n__ elements are mapped with the supplied mapping function
386 |
387 | ```java
388 | import static io.github.jhspetersson.packrat.Packrat.mapN;
389 | var mapped = IntStream.rangeClosed(1, 10).boxed().gather(mapN(5, n -> n * 10)).toList();
390 | System.out.println(mapped);
391 | ```
392 |
393 | > [10, 20, 30, 40, 50, 6, 7, 8, 9, 10]
394 |
395 | #### skipAndMap
396 |
397 | `skipAndMap(n, mapper)` - returns all elements that after the first __n__ are mapped with the supplied mapping function
398 |
399 | ```java
400 | import static io.github.jhspetersson.packrat.Packrat.skipAndMap;
401 | var mapped = IntStream.rangeClosed(1, 10).boxed().gather(skipAndMap(3, n -> n * 10)).toList();
402 | System.out.println(mapped);
403 | ```
404 |
405 | > [1, 2, 3, 40, 50, 60, 70, 80, 90, 100]
406 |
407 | #### skipAndMapN
408 |
409 | `skipAndMapN(skipN, mapN, mapper)` - returns all elements, after __skipN__ elements the first __mapN__ elements are mapped with the supplied mapping function
410 |
411 | ```java
412 | import static io.github.jhspetersson.packrat.Packrat.skipAndMapN;
413 | var mapped = IntStream.rangeClosed(1, 10).boxed().gather(skipAndMapN(3, 5, n -> n * 10)).toList();
414 | System.out.println(mapped);
415 | ```
416 |
417 | > [1, 2, 3, 40, 50, 60, 70, 80, 9, 10]
418 |
419 | #### mapWhile
420 |
421 | `mapWhile(predicate, mapper)` - maps elements using the supplied function while the predicate evaluates to true
422 |
423 | ```java
424 | import static io.github.jhspetersson.packrat.Packrat.mapWhile;
425 | var numbers = IntStream.rangeClosed(1, 10).boxed().gather(mapWhile(n -> n * 10, n -> n < 5)).toList();
426 | System.out.println(numbers);
427 | ```
428 |
429 | > [10, 20, 30, 40, 5, 6, 7, 8, 9, 10]
430 |
431 | #### mapUntil
432 |
433 | `mapUntil(predicate, mapper)` - maps elements using the supplied function until the predicate evaluates to false
434 |
435 | ```java
436 | import static io.github.jhspetersson.packrat.Packrat.mapUntil;
437 | var numbers = IntStream.rangeClosed(1, 10).boxed().gather(mapUntil(n -> n * 10, n -> n == 5)).toList();
438 | System.out.println(numbers);
439 | ```
440 |
441 | > [10, 20, 30, 40, 5, 6, 7, 8, 9, 10]
442 |
443 | ### Collection and chunking operations
444 |
445 | #### increasingChunks
446 |
447 | `increasingChunks()` - returns lists ("chunks") of elements, where each next element is greater than the previous one
448 |
449 | ```java
450 | import static io.github.jhspetersson.packrat.Packrat.increasingChunks;
451 | var numbers = Stream.of(1, 2, 2, 5, 4, 2, 6, 9, 3, 11, 0, 1, 20);
452 | var result = numbers.gather(increasingChunks()).toList();
453 | System.out.println(result);
454 | ```
455 |
456 | > [[1, 2], [2, 5], [4], [2, 6, 9], [3, 11], [0, 1, 20]]
457 |
458 | #### increasingOrEqualChunks
459 |
460 | `increasingOrEqualChunks()` - returns lists ("chunks") of elements, where each next element is greater or equal than the previous one
461 |
462 | ```java
463 | import static io.github.jhspetersson.packrat.Packrat.increasingOrEqualChunks;
464 | var numbers = Stream.of(1, 2, 2, 5, 4, 2, 6, 9, 3, 11, 0, 1, 20);
465 | var result = numbers.gather(increasingOrEqualChunks()).toList();
466 | System.out.println(result);
467 | ```
468 |
469 | > [[1, 2, 2, 5], [4], [2, 6, 9], [3, 11], [0, 1, 20]]
470 |
471 | #### equalChunks
472 |
473 | `equalChunks()` - returns lists ("chunks") of elements, where all elements in a chunk are equal to each other
474 |
475 | ```java
476 | import static io.github.jhspetersson.packrat.Packrat.equalChunks;
477 | var numbers = Stream.of(1, 1, 2, 2, 2, 3, 4, 4, 5, 5, 5, 5, 6);
478 | var result = numbers.gather(equalChunks()).toList();
479 | System.out.println(result);
480 | ```
481 |
482 | > [[1, 1], [2, 2, 2], [3], [4, 4], [5, 5, 5, 5], [6]]
483 |
484 | `equalChunksBy(mapper)` - returns lists ("chunks") of elements, where all elements in a chunk have equal values after applying the mapper function
485 |
486 | ```java
487 | import static io.github.jhspetersson.packrat.Packrat.equalChunks;
488 | var strings = Stream.of("apple", "apricot", "banana", "blueberry", "cherry", "date");
489 | var result = strings.gather(equalChunks(s -> s.charAt(0))).toList();
490 | System.out.println(result);
491 | ```
492 |
493 | > [[apple, apricot], [banana, blueberry], [cherry], [date]]
494 |
495 | `equalChunks(comparator)` - returns lists ("chunks") of elements, where all elements in a chunk are equal according to the supplied comparator
496 |
497 | ```java
498 | import static io.github.jhspetersson.packrat.Packrat.equalChunks;
499 | // Case-insensitive string comparison
500 | var strings = Stream.of("Apple", "apple", "Banana", "banana", "Cherry", "cherry");
501 | var result = strings.gather(equalChunks(String.CASE_INSENSITIVE_ORDER)).toList();
502 | System.out.println(result);
503 | ```
504 |
505 | > [[Apple, apple], [Banana, banana], [Cherry, cherry]]
506 |
507 | `equalChunksBy(mapper, comparator)` - returns lists ("chunks") of elements, where all elements in a chunk have equal values after applying the mapper function, with equality determined by the supplied comparator
508 |
509 | ```java
510 | import static io.github.jhspetersson.packrat.Packrat.equalChunks;
511 | record Person(String name, String id) {}
512 |
513 | // Group people by the first letter of their ID, case-insensitive
514 | var people = Stream.of(
515 | new Person("John", "A123"),
516 | new Person("Alice", "a456"),
517 | new Person("Bob", "B789"),
518 | new Person("Charlie", "b012"),
519 | new Person("David", "C345"),
520 | new Person("Eve", "c678")
521 | );
522 |
523 | var result = people.gather(equalChunks(
524 | p -> p.id().substring(0, 1), // Map to first letter of ID
525 | String.CASE_INSENSITIVE_ORDER // Compare case-insensitive
526 | )).toList();
527 |
528 | System.out.println(result);
529 | ```
530 |
531 | > [[Person[name=John, id=A123], Person[name=Alice, id=a456]], [Person[name=Bob, id=B789], Person[name=Charlie, id=b012]], [Person[name=David, id=C345], Person[name=Eve, id=c678]]]
532 |
533 | #### decreasingChunks
534 |
535 | `decreasingChunks()` - returns lists ("chunks") of elements, where each next element is less than the previous one
536 |
537 | #### decreasingOrEqualChunks
538 |
539 | `decreasingOrEqualChunks()` - returns lists ("chunks") of elements, where each next element is less or equal than the previous one
540 |
541 | #### nCopies
542 |
543 | `nCopies(n)` - returns __n__ copies of every element, __n__ less than or equal to zero effectively empties the stream
544 |
545 | ```java
546 | import static io.github.jhspetersson.packrat.Packrat.nCopies;
547 | var numbers = IntStream.of(5).boxed().gather(nCopies(10)).toList();
548 | System.out.println(numbers);
549 | ```
550 |
551 | > [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
552 |
553 | #### repeat
554 |
555 | `repeat(n)` - collects the whole stream and repeats it __n__ times, __n__ equal to zero effectively empties the stream
556 |
557 | ```java
558 | import static io.github.jhspetersson.packrat.Packrat.repeat;
559 | var numbers = Stream.of(1, 2, 3).gather(repeat(2)).toList();
560 | System.out.println(numbers);
561 | ```
562 |
563 | > [1, 2, 3, 1, 2, 3]
564 |
565 | > [!CAUTION]
566 | > This gatherer will consume the entire stream before producing any output.
567 |
568 | #### atLeast
569 |
570 | `atLeast(n)` - returns distinct elements that appear at least __n__ times in the stream
571 |
572 | ```java
573 | import static io.github.jhspetersson.packrat.Packrat.atLeast;
574 | var numbers = Stream.of(1, 2, 3, 3, 3, 4, 5, 5, 6, 7, 8, 8, 8, 8, 9, 10);
575 | var atLeastThree = numbers.gather(atLeast(3)).toList();
576 | System.out.println(atLeastThree);
577 | ```
578 | > [3, 3, 3, 8, 8, 8, 8]
579 |
580 | #### atMost
581 |
582 | `atMost(n)` - returns distinct elements that appear at most __n__ times in the stream
583 |
584 | ```java
585 | import static io.github.jhspetersson.packrat.Packrat.atMost;
586 | var numbers = Stream.of(1, 2, 3, 3, 3, 4, 5, 5, 6, 7, 8, 8, 8, 8, 9, 10);
587 | var atMostTwo = numbers.gather(atMost(2)).toList();
588 | System.out.println(atMostTwo);
589 | ```
590 | > [1, 2, 4, 5, 5, 6, 7, 9, 10]
591 |
592 | `atMostBy(n, mapper)` - returns distinct elements mapped by the supplied function that appear at most __n__ times in the stream
593 |
594 | ```java
595 | import static io.github.jhspetersson.packrat.Packrat.atMostBy;
596 | var strings = Stream.of("apple", "banana", "cherry", "date", "elderberry", "fig", "grape");
597 | var uniqueLengths = strings.gather(atMostBy(1, String::length)).toList();
598 | System.out.println(uniqueLengths);
599 | ```
600 | > [date, elderberry, fig]
601 |
602 | > [!CAUTION]
603 | > This gatherer will consume the entire stream before producing any output.
604 |
605 | ### Indexing and zipping operations
606 |
607 | #### zip
608 |
609 | `zip(input, mapper)` - returns elements mapped ("zipped") with the values from some other stream, iterable or iterator.
610 |
611 | ```java
612 | import static io.github.jhspetersson.packrat.Packrat.zip;
613 | var names = List.of("Anna", "Mike", "Sandra");
614 | var ages = Stream.of(20, 30, 40, 50, 60, 70, 80, 90);
615 | var users = names.stream().gather(zip(ages, User::new)).toList();
616 | System.out.println(users);
617 | ```
618 |
619 | > [User[name=Anna, age=20], User[name=Mike, age=30], User[name=Sandra, age=40]]
620 |
621 | `zip(input)` - zips current stream and input into Map entries.
622 |
623 | ```java
624 | import static io.github.jhspetersson.packrat.Packrat.zip;
625 | var names = List.of("Anna", "Mike", "Sandra");
626 | var ages = Stream.of(20, 30, 40);
627 | var users = names.stream().gather(zip(ages)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
628 | System.out.println(users);
629 | ```
630 |
631 | > {Mike=30, Anna=20, Sandra=40}
632 |
633 | #### zipWithIndex
634 |
635 | `zipWithIndex()` - zips current stream with an increasing index into Map entries.
636 |
637 | ```java
638 | import static io.github.jhspetersson.packrat.Packrat.zipWithIndex;
639 | var names = List.of("Anna", "Mike", "Sandra");
640 | var users = names.stream().gather(zipWithIndex()).toList();
641 | ```
642 |
643 | > [0=Anna, 1=Mike, 2=Sandra]
644 |
645 | `zipWithIndex(startIndex)` - zips current stream with an increasing index (beginning with _startIndex_) into Map entries.
646 |
647 | ```java
648 | import static io.github.jhspetersson.packrat.Packrat.zipWithIndex;
649 | var names = List.of("Anna", "Mike", "Sandra");
650 | var users = names.stream().gather(zipWithIndex(10)).toList();
651 | ```
652 |
653 | > [10=Anna, 11=Mike, 12=Sandra]
654 |
655 | `mapWithIndex(mapper)` or `zipWithIndex(mapper)` - maps/zips current stream with an increasing index, mapping function receives the index as the first argument.
656 |
657 | ```java
658 | import static io.github.jhspetersson.packrat.Packrat.zipWithIndex;
659 | var names = List.of("Anna", "Mike", "Sandra");
660 | var users = names.stream().gather(zipWithIndex(User::new)).toList();
661 | ```
662 |
663 | > [User[index=0, name=Anna], User[index=1, name=Mike], User[index=2, name=Sandra]]
664 |
665 | `mapWithIndex(mapper, startIndex)` or `zipWithIndex(mapper, startIndex)` - maps/zips current stream with an increasing index (beginning with _startIndex_), mapping function receives the index as the first argument.
666 |
667 | ```java
668 | import static io.github.jhspetersson.packrat.Packrat.zipWithIndex;
669 | var names = List.of("Anna", "Mike", "Sandra");
670 | var users = names.stream().gather(zipWithIndex(User::new, 10)).toList();
671 | ```
672 |
673 | > [User[index=10, name=Anna], User[index=11, name=Mike], User[index=12, name=Sandra]]
674 |
675 | #### peekWithIndex
676 |
677 | `peekWithIndex(consumer)` - peeks at each element along with its index (starting from 0), but passes the original element downstream unchanged
678 |
679 | ```java
680 | import static io.github.jhspetersson.packrat.Packrat.peekWithIndex;
681 | var names = List.of("Anna", "Mike", "Sandra");
682 | var result = names.stream().gather(peekWithIndex((index, name) ->
683 | System.out.println("Element at index " + index + ": " + name))).toList();
684 | System.out.println(result);
685 | ```
686 |
687 | > Element at index 0: Anna
688 | > Element at index 1: Mike
689 | > Element at index 2: Sandra
690 | > [Anna, Mike, Sandra]
691 |
692 | `peekWithIndex(consumer, startIndex)` - peeks at each element along with its index (beginning with _startIndex_), but passes the original element downstream unchanged
693 |
694 | ```java
695 | import static io.github.jhspetersson.packrat.Packrat.peekWithIndex;
696 | var names = List.of("Anna", "Mike", "Sandra");
697 | var result = names.stream().gather(peekWithIndex((index, name) ->
698 | System.out.println("Element at index " + index + ": " + name), 10)).toList();
699 | System.out.println(result);
700 | ```
701 |
702 | > Element at index 10: Anna
703 | > Element at index 11: Mike
704 | > Element at index 12: Sandra
705 | > [Anna, Mike, Sandra]
706 |
707 | #### filterWithIndex
708 |
709 | `filterWithIndex(predicate)` - filters elements based on their index and a predicate, the index starts from 0
710 |
711 | ```java
712 | import static io.github.jhspetersson.packrat.Packrat.filterWithIndex;
713 | var numbers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
714 | var result = numbers.gather(filterWithIndex((index, element) -> index % 2 == 0)).toList();
715 | System.out.println(result);
716 | ```
717 |
718 | > [1, 3, 5, 7, 9]
719 |
720 | `filterWithIndex(predicate, startIndex)` - filters elements based on their index and a predicate, the index starts from _startIndex_
721 |
722 | ```java
723 | import static io.github.jhspetersson.packrat.Packrat.filterWithIndex;
724 | var numbers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
725 | var result = numbers.gather(filterWithIndex((index, element) -> index % 2 == 0, 1)).toList();
726 | System.out.println(result);
727 | ```
728 |
729 | > [2, 4, 6, 8, 10]
730 |
731 | #### removeWithIndex
732 |
733 | `removeWithIndex(predicate)` - removes elements based on their index and a predicate, the index starts from 0
734 |
735 | ```java
736 | import static io.github.jhspetersson.packrat.Packrat.removeWithIndex;
737 | var numbers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
738 | var result = numbers.gather(removeWithIndex((index, element) -> index % 2 == 0)).toList();
739 | System.out.println(result);
740 | ```
741 |
742 | > [2, 4, 6, 8, 10]
743 |
744 | `removeWithIndex(predicate, startIndex)` - removes elements based on their index and a predicate, the index starts from _startIndex_
745 |
746 | ```java
747 | import static io.github.jhspetersson.packrat.Packrat.removeWithIndex;
748 | var numbers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
749 | var result = numbers.gather(removeWithIndex((index, element) -> index % 2 == 0, 1)).toList();
750 | System.out.println(result);
751 | ```
752 |
753 | > [1, 3, 5, 7, 9]
754 |
755 | #### windowSlidingWithIndex
756 |
757 | `windowSlidingWithIndex(windowSize)` - returns fixed-size windows of elements along with their indices, the index starts from 0
758 |
759 | ```java
760 | import static io.github.jhspetersson.packrat.Packrat.windowSlidingWithIndex;
761 | var numbers = IntStream.rangeClosed(1, 5).boxed();
762 | var result = numbers.gather(windowSlidingWithIndex(3)).toList();
763 | System.out.println(result);
764 | ```
765 |
766 | > [0=[1, 2, 3], 1=[2, 3, 4], 2=[3, 4, 5]]
767 |
768 | `windowSlidingWithIndex(windowSize, startIndex)` - returns fixed-size windows of elements along with their indices, the index starts from _startIndex_
769 |
770 | ```java
771 | import static io.github.jhspetersson.packrat.Packrat.windowSlidingWithIndex;
772 | var numbers = IntStream.rangeClosed(1, 5).boxed();
773 | var result = numbers.gather(windowSlidingWithIndex(3, 10)).toList();
774 | System.out.println(result);
775 | ```
776 |
777 | > [10=[1, 2, 3], 11=[2, 3, 4], 12=[3, 4, 5]]
778 |
779 | `windowSlidingWithIndex(windowSize, mapper)` - returns fixed-size windows of elements along with their indices
780 | `windowSlidingWithIndex(windowSize, mapper, startIndex)` - returns fixed-size windows of elements along with their indices, the index starts from _startIndex_
781 |
782 | #### windowFixedWithIndex
783 |
784 | `windowFixedWithIndex(windowSize)` - returns fixed-size non-overlapping windows of elements along with their indices, the index starts from 0
785 |
786 | ```java
787 | import static io.github.jhspetersson.packrat.Packrat.windowFixedWithIndex;
788 | var numbers = IntStream.rangeClosed(1, 10).boxed();
789 | var result = numbers.gather(windowFixedWithIndex(3)).toList();
790 | System.out.println(result);
791 | ```
792 |
793 | > [0=[1, 2, 3], 1=[4, 5, 6], 2=[7, 8, 9]]
794 |
795 | `windowFixedWithIndex(windowSize, startIndex)` - returns fixed-size non-overlapping windows of elements along with their indices, the index starts from _startIndex_
796 |
797 | ```java
798 | import static io.github.jhspetersson.packrat.Packrat.windowFixedWithIndex;
799 | var numbers = IntStream.rangeClosed(1, 6).boxed();
800 | var result = numbers.gather(windowFixedWithIndex(2, 10)).toList();
801 | System.out.println(result);
802 | ```
803 |
804 | > [10=[1, 2], 11=[3, 4], 12=[5, 6]]
805 |
806 | `windowFixedWithIndex(windowSize, mapper)` - returns fixed-size non-overlapping windows of elements along with their indices
807 | `windowFixedWithIndex(windowSize, mapper, startIndex)` - returns fixed-size non-overlapping windows of elements along with their indices, the index starts from _startIndex_
808 |
809 | ### Element selection operations
810 |
811 | #### sample
812 |
813 | `sample(n)` - returns a sample of the specified size from the stream of elements.
814 |
815 | ```java
816 | import static io.github.jhspetersson.packrat.Packrat.sample;
817 | var source = IntStream.range(0, 100).boxed().gather(sample(10)).toList();
818 | System.out.println(source);
819 | ```
820 | > [0, 8, 27, 33, 65, 66, 88, 90, 93, 96]
821 |
822 | `sample(n, maxSpan)` - returns a sample of the specified size from the stream of elements, inspects first __maxSpan__ elements.
823 |
824 | #### nth
825 |
826 | `nth(n)` - takes every nth element from the stream
827 |
828 | ```java
829 | import static io.github.jhspetersson.packrat.Packrat.nth;
830 | var numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
831 | var result = numbers.stream().gather(nth(3)).toList();
832 | System.out.println(result);
833 | ```
834 |
835 | > [3, 6, 9]
836 |
837 | #### dropNth
838 |
839 | `dropNth(n)` - drops every nth element from the stream
840 |
841 | ```java
842 | import static io.github.jhspetersson.packrat.Packrat.dropNth;
843 | var numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
844 | var result = numbers.stream().gather(dropNth(3)).toList();
845 | System.out.println(result);
846 | ```
847 |
848 | > [1, 2, 4, 5, 7, 8, 10]
849 |
850 | #### last
851 |
852 | `last()` - returns last element from the stream.
853 |
854 | ```java
855 | import static io.github.jhspetersson.packrat.Packrat.last;
856 | var integers = IntStream.range(0, 100).boxed().gather(last()).toList();
857 | System.out.println(integers);
858 | ```
859 |
860 | > [99]
861 |
862 | `last(n)` - returns __n__ last elements from the stream.
863 |
864 | ```java
865 | import static io.github.jhspetersson.packrat.Packrat.last;
866 | var integers = IntStream.range(0, 100).boxed().gather(last(10)).toList();
867 | System.out.println(integers);
868 | ```
869 |
870 | > [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
871 |
872 | > [!CAUTION]
873 | > This gatherer will consume the entire stream before producing any output.
874 |
875 | #### lastUnique
876 |
877 | `lastUnique(n)` - returns __n__ last unique elements from the stream.
878 |
879 | ```java
880 | import static io.github.jhspetersson.packrat.Packrat.lastUnique;
881 | var integers = List.of(1, 2, 3, 4, 5, 4, 1, 1, 1, 2, 2, 6).stream().gather(lastUnique(3)).toList();
882 | System.out.println(integers);
883 | ```
884 |
885 | > [1, 2, 6]
886 |
887 | > [!CAUTION]
888 | > This gatherer will consume the entire stream before producing any output.
889 |
890 | #### dropLast
891 |
892 | `dropLast()` - drops last element.
893 |
894 | `dropLast(n)` - drops last __n__ elements from the stream.
895 |
896 | ```java
897 | import static io.github.jhspetersson.packrat.Packrat.dropLast;
898 | var integers = IntStream.range(0, 10).boxed().gather(dropLast(3)).toList();
899 | System.out.println(integers);
900 | ```
901 |
902 | > [0, 1, 2, 3, 4, 5, 6]
903 |
904 | > [!CAUTION]
905 | > This gatherer will consume the entire stream before producing any output.
906 |
907 | ### Text processing operations
908 |
909 | #### chars
910 |
911 | `chars()` - returns characters as strings parsed from the stream elements
912 |
913 | ```java
914 | import static io.github.jhspetersson.packrat.Packrat.chars;
915 | var charStrings = Stream.of("Hello, \uD83D\uDC22!").gather(chars()).toList();
916 | System.out.println(charStrings);
917 | ```
918 |
919 | > [H, e, l, l, o, ,, , 🐢, !]
920 |
921 | #### words
922 |
923 | `words()` - returns words as strings parsed from the stream elements
924 |
925 | ```java
926 | import static io.github.jhspetersson.packrat.Packrat.words;
927 | var wordStrings = Stream.of("Another test!").gather(words()).toList();
928 | System.out.println(wordStrings);
929 | ```
930 |
931 | > [Another, test, !]
932 |
933 | #### sentences
934 |
935 | `sentences()` - returns sentences as strings parsed from the stream elements
936 |
937 | ```java
938 | import static io.github.jhspetersson.packrat.Packrat.sentences;
939 | var sentenceStrings = Stream.of("And another one. How many left?").gather(sentences()).toList();
940 | System.out.println(sentenceStrings);
941 | ```
942 |
943 | > [And another one. , How many left?]
944 |
945 | ### Utility operations
946 |
947 | #### asGatherer
948 |
949 | `asGatherer(collector)` - provides the result of the supplied collector as a single element into the stream, effectively converts any Collector into a Gatherer
950 |
951 | ```java
952 | import static io.github.jhspetersson.packrat.Packrat.asGatherer;
953 | var numbers = Stream.of(1, 2, 3, 4, 5);
954 | var listOfCollectedList = numbers.gather(asGatherer(Collectors.toList())).toList();
955 | System.out.println(listOfCollectedList);
956 | ```
957 |
958 | > [[1, 2, 3, 4, 5]]
959 |
960 | #### identity
961 |
962 | `identity()` - returns a gatherer that passes elements through unchanged
963 |
964 | ```java
965 | import static io.github.jhspetersson.packrat.Packrat.identity;
966 | var numbers = IntStream.range(0, 5).boxed();
967 | var sameNumbers = numbers.gather(identity()).toList();
968 | System.out.println(sameNumbers);
969 | ```
970 |
971 | > [0, 1, 2, 3, 4]
972 |
973 | ### License
974 |
975 | Apache-2.0
976 |
977 | ---
978 | Supported by [JetBrains IDEA](https://jb.gg/OpenSourceSupport) open source license.
979 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'java-library'
3 | id 'maven-publish'
4 | }
5 |
6 | group = 'io.github.jhspetersson'
7 | version = '0.2.0'
8 |
9 | repositories {
10 | mavenCentral()
11 | }
12 |
13 | dependencies {
14 | compileOnly 'org.jspecify:jspecify:1.0.0'
15 | testImplementation platform('org.junit:junit-bom:5.11.2')
16 | testImplementation 'org.junit.jupiter:junit-jupiter'
17 | testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
18 | }
19 |
20 | test {
21 | useJUnitPlatform()
22 | }
23 |
24 | jar {
25 | manifest {
26 | attributes('Implementation-Title': project.name,
27 | 'Implementation-Version': project.version)
28 | }
29 | }
30 |
31 | tasks.register('sourcesJar', Jar) {
32 | archiveClassifier.set('sources')
33 | from sourceSets.main.allSource
34 | }
35 |
36 | tasks.register('javadocJar', Jar) {
37 | archiveClassifier.set('javadoc')
38 | from tasks.javadoc
39 | }
40 |
41 | artifacts {
42 | archives sourcesJar
43 | archives javadocJar
44 | }
45 |
46 | publishing {
47 | publications {
48 | myPublication(MavenPublication) {
49 | from components.java
50 |
51 | pom {
52 | name = "${project.name}"
53 | description = 'Gatherers library for Java Stream API'
54 | url = 'https://github.com/jhspetersson/packrat'
55 |
56 | licenses {
57 | license {
58 | name = 'The Apache License, Version 2.0'
59 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
60 | }
61 | }
62 |
63 | developers {
64 | developer {
65 | name = 'Ivan Petrichenko'
66 | email = 'jhspetersson@gmail.com'
67 | organizationUrl = 'https://github.com/jhspetersson'
68 | }
69 | }
70 |
71 | scm {
72 | connection = 'scm:git://github.com/jhspetersson/packrat.git'
73 | developerConnection = 'scm:git:ssh://github.com/jhspetersson/packrat.git'
74 | url = 'https://github.com/jhspetersson/packrat'
75 | }
76 | }
77 | }
78 | }
79 |
80 | repositories {
81 | maven {
82 | url = layout.buildDirectory.dir('fake-repo')
83 | }
84 | }
85 | }
86 |
87 | tasks.register('generatePom', GenerateMavenPom) {
88 | group = 'build'
89 | description = 'Generates the POM file without publishing.'
90 | destination = file("${layout.buildDirectory.asFile.get()}/libs/${rootProject.name}-${project.version}.pom")
91 | pom = publishing.publications.myPublication.pom
92 |
93 | doLast {
94 | println "POM file written to: ${destination}"
95 | }
96 | }
97 |
98 | build.finalizedBy {
99 | tasks.generatePom
100 | }
101 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jhspetersson/packrat/30560b76565e640ad44fca27aab7bbe59de288b9/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Use "xargs" to parse quoted args.
209 | #
210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
211 | #
212 | # In Bash we could simply go:
213 | #
214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
215 | # set -- "${ARGS[@]}" "$@"
216 | #
217 | # but POSIX shell has neither arrays nor command substitution, so instead we
218 | # post-process each arg (as a line of input to sed) to backslash-escape any
219 | # character that might be a shell metacharacter, then use eval to reverse
220 | # that process (while maintaining the separation between arguments), and wrap
221 | # the whole thing up as a single "set" statement.
222 | #
223 | # This will of course break if any of these variables contains a newline or
224 | # an unmatched quote.
225 | #
226 |
227 | eval "set -- $(
228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
229 | xargs -n1 |
230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
231 | tr '\n' ' '
232 | )" '"$@"'
233 |
234 | exec "$JAVACMD" "$@"
235 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'packrat'
--------------------------------------------------------------------------------
/src/main/java/io/github/jhspetersson/packrat/AtLeastGatherer.java:
--------------------------------------------------------------------------------
1 | package io.github.jhspetersson.packrat;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.List;
6 | import java.util.Map;
7 | import java.util.Objects;
8 | import java.util.function.Function;
9 | import java.util.function.Supplier;
10 | import java.util.stream.Gatherer;
11 |
12 | /**
13 | * Returns distinct elements that appear at least n
times in the stream.
14 | *
15 | * @param element type
16 | * @param mapped element type
17 | * @author jhspetersson
18 | */
19 | class AtLeastGatherer implements Gatherer>, T> {
20 | private final long atLeast;
21 | private final Function super T, ? extends U> mapper;
22 |
23 | AtLeastGatherer(long atLeast, Function super T, ? extends U> mapper) {
24 | if (atLeast < 0) {
25 | throw new IllegalArgumentException("atLeast must be a non-negative number");
26 | }
27 | Objects.requireNonNull(mapper, "mapper cannot be null");
28 |
29 | this.atLeast = atLeast;
30 | this.mapper = mapper;
31 | }
32 |
33 | @Override
34 | public Supplier