If I have a Name
object and have an ArrayList
of type Name
(names
), and I want to ascertain whether my list of names contains a given Name
object (n
), I could do it two ways:
boolean exists = names.contains(n);
or
boolean exists = names.stream().anyMatch(x -> x.equals(n));
I was considering if these two would behave the same and then thought about what happens if n was assigned null
?
For contains, as I understand, if the argument is null
, then it returns true
if the list contains null
. How would I achieve this anyMatch
- would it be by using Objects.equals(x, n)
?
If that is how it works, then which approach is more efficient - is it anyMatch
as it can take advantage of laziness and parallelism?