Java 8 Stream.skip with Predicate [duplicate]

核能气质少年 提交于 2019-12-12 17:04:01

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/35791075/java-8-stream-skip-with-predicate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!