简体   繁体   English

Java Streams,仅过滤前“ N”个匹配项

[英]Java Streams, filter only the first 'N' matches

is there any way to filter only the first 'n' matches using java streams? 有什么方法可以使用Java流仅过滤第一个“ n”个匹配项?

for example, if we have this code: 例如,如果我们有以下代码:

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);

this will filter all "one" strings from the word stream. 这将从单词流中过滤所有“一个”字符串。

So, how to filter only the first 'n' matches and keep the rest of the stream intact? 那么,如何过滤前“ n”个匹配项并保持流的其余部分不变?

in other words, if n=1 then, the program should output 换句话说,如果n = 1,则程序应输出

"zero","two","three","four","five","one","one"

if n=2 then 如果n = 2那么

"zero","two","three","four","five","one" “零”,“二”,“三”,“四有”,“五”,“一”

You can create a class doing the filtering for you 您可以创建一个类为您进行过滤

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;
    }
}

and then use it to filter 然后用它来过滤

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());

This may Help full for you check it out 这可能会帮助您完成全部检查

 List<String> 
words = Arrays.asList("zero","one","two","three","four","five","one","one");

    Stream<String> sortedList =  words.stream().filter(word -> 
     word.contains("n"));

    sortedList.forEach(str->System.out.println(str));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM