3

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?

Balazs
  • 185
  • 1
  • 3
  • 10

1 Answers1

7

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
Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130