gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:19:18 25 4
gpt4 key购买 nike

我想查找字符串流是否至少出现一次另一个 StringSet<String> .我想到了两个解决方案。

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

1)

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

2)

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

这是 streamFilter 方法:

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

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

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

最佳答案

你应该使用anyMatch(this::streamFilter),看看API在下面的 anyMatch 方法上(强调我的)因为 它可能不会评估流的所有元素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.

重点是一些流方法,如 findFirst()anyMatch()findAny() 等。执行 < strong>短路操作 即,它们可能不会评估流的所有元素,您可以引用 here了解更多详情。

关于Java 流 : filter(). count() 与 anyMatch(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43312883/

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