The problem with the stream-based version is that if the collection (and thus its stream) contains null
elements, then the predicate will throw a NullPointerException
when it tries to call equals
on this null
object.
This could be avoided with
boolean exists = names.stream().anyMatch(x -> Objects.equals(x, n));
But there is no practical advantage to be expected for the stream-based solution in this case. Parallelism might bring an advantage for really large lists, but one should not casually throw in some parallel()
here and there assuming that it may make things faster. First, you should clearly identify the actual bottlenecks.
And in terms of readability, I'd prefer the first, classical solution here. If you want to check whether the list of names.contains(aParticularValue)
, you should do this - it just reads like prose and makes the intent clear.
EDIT
Another advantage of the contains
approach was mentioned in the comments and in the other answer, and that may be worth mentioning here: If the type of the names
collection is later changed, for example, to be a HashSet
, then you'll get the faster contains
-check (with O(1) instead of O(n)) for free - without changing any other part of the code. The stream-based solution would then still have to iterate over all elements, and this could have a significantly lower performance.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…