Java Streams:filter().count() 与 anyMatch()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43312883/
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-11-03 07:20:06  来源:igfitidea点击:

Java Streams: filter().count() vs anyMatch()

javajava-8java-stream

提问by dazito

I want to find if a stream of strings has at least one occurrence of another Stringin a Set<String>. I came up with two solutions.

我想找到,如果字符串流具有的另一个至少一个出现StringSet<String>。我想出了两个解决方案。

Performance wise, which approach is the best/recommended?

性能方面,哪种方法最好/推荐?

1)

1)

return source.stream().filter(this::streamFilter).count() > 0;

2)

2)

return source.stream().anyMatch(this::streamFilter);

Here's streamFilter method:

这是 streamFilter 方法:

private boolean streamFilter(String str) {
    return filterKeywords.contains(str.toLowerCase());
}

filterKeywords: private Set<String> filterKeywords;

过滤关键字: private Set<String> filterKeywords;

Or is there better approach than this?

或者有比这更好的方法吗?

回答by developer

You should use anyMatch(this::streamFilter), look at the APIon the anyMatchmethod below (emphasis mine) as it may not evaluate all elementsof the stream where as count()obviously iterates the whole stream of elements.

你应该用anyMatch(this::streamFilter)的,看APIanyMatch下方(重点煤矿)方法,它可能无法评估所有的元素,其中作为流的count()明显迭代元素的全码流。

Returns whether any elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then false is returned and the predicate is not evaluated.

返回此流的任何元素是否与提供的谓词匹配。如果不是确定结果所必需的,则可以不对所有元素评估谓词。如果流为空,则返回 false 并且不评估谓词。

The point is some of the stream methods like findFirst(), anyMatch(), findAny(), etc.. perform short-circuiting operationsi.e., they may not evaluate all elements of the stream and you can refer herefor more details.

重点是一些流方法,如findFirst()anyMatch()findAny()等......执行短路操作,即,它们可能不会评估流的所有元素,您可以参考此处了解更多详细信息。

回答by DJAM Silvère Gatien

anyMatch doesn't always execute all the stream. It is the best approach.

anyMatch 并不总是执行所有的流。这是最好的方法。