-
Notifications
You must be signed in to change notification settings - Fork 251
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding sliding() implementation #158
Comments
I'm reluctant to implement it as built-in operation, because it's hard to implement efficient parallel version. Test demonstrates how you can do it in your project if you need it. If you want slides of two elements, use |
Ok, and could you tell why |
There's no thing like
|
Ok, there is no thing like that, how do I solve problem where I need to split stream by equally sized portions without loading all its content in memory? |
Currently you may create utility methods in your project like it's demonstrated in tests. Write in utility class: private static <T> StreamEx<List<T>> sliding(StreamEx<List<T>> input, int size) {
return input.headTail((head, tail) -> head.size() == size ? sliding(
tail.mapFirst(next -> StreamEx.of(head.subList(1, size), next).toFlatList(l -> l)), size).prepend(head)
: sliding(tail.mapFirst(next -> StreamEx.of(head, next).toFlatList(l -> l)), size));
}
public static <T> Function<StreamEx<T>, StreamEx<List<T>>> sliding(int size) {
return s -> sliding(s.map(Collections::singletonList), size);
} Use: StreamEx.of(1,2,3,4,5).chain(sliding(3)).forEach(System.out::println); Output: [1, 2, 3]
[2, 3, 4]
[3, 4, 5] |
yeah, and for non-overlapping case - just to set some other params? |
For batches there's another sample. In utility class: private static <T> StreamEx<List<T>> batches(StreamEx<T> input, int size, List<T> cur) {
return input.headTail((head, tail) -> cur.size() >= size
? batches(tail, size, asList(head)).prepend(cur)
: batches(tail, size, StreamEx.of(cur).append(head).toList()),
() -> Stream.of(cur));
}
public static <T> Function<StreamEx<T>, StreamEx<List<T>>> batches(int size) {
return s -> batches(s, size, Collections.emptyList());
} Use: StreamEx.of(1,2,3,4,5,6,7,8).chain(batches(3)).forEach(System.out::println); Output: [1, 2, 3]
[4, 5, 6]
[7, 8] |
Thank you! |
Is it possible to add
sliding()
to StreamEx? Now I found it only in tests.The text was updated successfully, but these errors were encountered: