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

时间:2017-04-09 23:11:04

标签: java java-8 java-stream

我想查找字符串流是否在String中至少有一次出现另一个Set<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());
}

filterKeywords:private Set<String> filterKeywords;

或者有更好的方法吗?

2 个答案:

答案 0 :(得分:21)

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

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.

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

答案 1 :(得分:1)

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