有什么方法可以使用java流仅过滤前“n”个匹配项?
例如,如果我们有这个代码:
List<String> words = Arrays.asList("zero","one","two","three","four","five","one","one");
List<String> filteredWords = words.stream()
.filter(word->!word.equals("one"))//filter all "one" strings..
.collect(Collectors.toList());
System.out.println(filteredWords);
这将从单词流中过滤所有“一”字符串。
那么,如何仅过滤前“n”个匹配项并保持流的其余部分完整无缺?
换句话说,如果 n=1 那么程序应该输出
"zero","two","three","four","five","one","one"
如果 n=2 那么
“零”、“二”、“三”、“四”、“五”、“一”
您可以创建一个类为您进行过滤
class LimitedFilter<T> implements Predicate<T> {
int matches = 0;
final int limit;
private Predicate<T> delegate;
public LimitedFilter<T>(Predicate<T> p, int limit) {
delegate = p; this.limit = limit;
}
public boolean test(T toTest) {
if (matches > limit) return true;
boolean result = delegate.test(toTest);
if (result) matches++;
return result;
}
}
然后用它来过滤
Predicate<String> limited = new LimitedFilter<>(w -> !"one".equals(w), 5);
List<String> filteredWords = words.stream()
.filter(limited) //filter first five "one" strings..
.collect(Collectors.toList());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句