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
How to filter list using Predicate
提问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 Predicate
here 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。