Java 8 Stream.skip with Predicate [英] Java 8 Stream.skip with Predicate
本文介绍了Java 8 Stream.skip with Predicate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法做类似于Stream.skip(long)但使用Predicate而不是确切的数字?
Is there any way to do something similar to Stream.skip(long) but using Predicate instead of an exact number?
我需要跳过元素直到达到一个具有给定ID,然后我需要继续应用过滤器,限制等任何建议?
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?
推荐答案
编辑:更多简明版本是 https://stackoverflow.com/a/52270820/57695
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));
}
}
在流中
你可以这样做
Stream.of(1,2,3,4,5)
.filter(from(i -> i % 2 == 0)))
.forEach(System.out::println);
应打印
2
3
4
5
这篇关于Java 8 Stream.skip with Predicate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文