java 如何使用 Predicate 过滤列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9877780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:44:48  来源:igfitidea点击:

How to filter list using Predicate

java

提问by Zugdud

private static class FilterByStringContains implements Predicate<String> {
        private String filterString;
        private FilterByStringContains(final String filterString) {
            this.filterString = filterString;
        }
        @Override
        public boolean apply(final String string) {
            return string.contains(filterString);
        }
    }

I have a list of Strings, I want to filter it by the specified String so the returned value contains a list of only the specified strings. I was going to use a predicate as above but not sure how to apply this to filter a list

我有一个字符串列表,我想按指定的字符串对其进行过滤,以便返回的值仅包含指定字符串的列表。我打算使用上面的谓词,但不确定如何应用它来过滤列表

回答by Jon Skeet

I'm assuming the Predicatehere is from Guava? If so, you could use Iterables.filter:

我假设Predicate这里来自番石榴?如果是这样,您可以使用Iterables.filter

Iterable<String> filtered = Iterables.filter(original, predicate);

Then build a list from that if you wanted:

如果需要,然后从中构建一个列表:

List<String> filteredCopy = Lists.newArrayList(filtered);

... but I'd onlysuggest copying it to another list if you actually want it as a list. If you're just going to iterate over it (and only once), stick to the iterable.

...但我建议将它复制到另一个列表,如果你真的想要它作为一个列表。如果您只是要迭代它(并且只迭代一次),请坚持使用 iterable。

回答by óscar López

How about using Guava's filtermethod or Apache commons' filtermethod? Guava's method returns a view of the collection, whereas Apache Commons' modifies the collection in-place. Don't reinvent the wheel!

用Guava的过滤方式或者Apache commons的过滤方式怎么样?Guava 的方法返回集合的视图,而 Apache Commons 的方法就地修改集合。不要重新发明轮子!