Is there any way to do something similar to Stream.skip(long) but using Predicate instead of an exact number?
I need to skip elements until I reach one with a given ID and then I would need to continue applying filters, limit etc. Any suggestion?
Is there any way to do something similar to Stream.skip(long) but using Predicate instead of an exact number?
I need to skip elements until I reach one with a given ID and then I would need to continue applying filters, limit etc. Any suggestion?
EDIT: A more concise version is https://stackoverflow.com/a/52270820/57695
I suspect you need to write a stateful predicate or use a wrapper like
public class FromPredicate<T> implements Predicate<T> {
boolean started = false;
Predicate<T> test;
FromPredicate(Predicate<T> test) { this.test = test; }
public static Predicate<T> from(Predicate<T> test) { return new FromPredicate<>(test); }
public boolean test(T t) {
return started || (started = test.test(t));
}
}
In a Stream
you could then do
Stream.of(1,2,3,4,5)
.filter(from(i -> i % 2 == 0)))
.forEach(System.out::println);
Should print
2
3
4
5