gpt4 book ai didi

Java Streams,仅过滤第一个 'N' 匹配项

转载 作者:行者123 更新时间:2023-11-30 02:13:05 24 4
gpt4 key购买 nike

有没有办法使用 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);

这将从单词流中过滤掉所有“one”字符串。

那么,如何过滤前“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());

关于Java Streams,仅过滤第一个 'N' 匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49527272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com