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.

Answer from Marco13 on Stack Overflow
Top answer
1 of 2
68

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.

2 of 2
4

They should provide the same result if hashCode() and equals() are written in reasonable way.

But the performance may be completely different. For Lists it wouldn't matter that much but for HashSet contains() will use hashCode() to locate the element and it will be done (most probably) in constant time. While with the second solution it will loop over all items and call a function so will be done in linear time.

If n is null, actually doesn't matter as usually equals() methods are aware of null arguments.

🌐
Java Code Geeks
javacodegeeks.com › home › core java
Java Stream contains, containsAny and containsAll examples - Java Code Geeks
June 24, 2024 - While contains() is directly available in the Java Collection framework, containsAny() can be efficiently implemented using Java 8 Streams to check for the presence of any elements from one collection in another.
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java stream anymatch()
Java Stream anyMatch() with Examples - HowToDoInJava
December 12, 2022 - Java Stream anyMatch(predicate) is a terminal short-circuit operation. It is used to check if the Stream contains at least one element that satisfies the given Predicate.
🌐
How to do in Java
howtodoinjava.com › home › java streams › java stream contains, containsany and containsall examples
Java Stream contains, containsAny and containsAll Examples
May 2, 2024 - Assertions.assertTrue( StreamUtils.containsAll(cars.stream(), car1) ); Assertions.assertFalse( StreamUtils.containsAll(cars.stream(), car1, car3) ); Assertions.assertTrue( StreamUtils.containsAll(cars.stream(), List.of(car1)) ); Assertions.assertFalse( StreamUtils.containsAll(cars.stream(), Stream.of(car2)) ); In this short Java tutorial, we created a Java Stream utility class and added the contains, containsAny and containsAll methods.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › stream › Stream.html
Stream (Java Platform SE 8 )
2 weeks ago - Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.
🌐
Baeldung
baeldung.com › home › java › java list › check if a list contains an element from another list in java
Check if a List Contains an Element From Another List in Java | Baeldung
May 7, 2025 - As shown above, we find a match as both Lists contain a Spanish-speaking country. In this article, we’ve seen that Streams are the most versatile solution to this problem. We can easily use them to compare entire objects or properties within the objects. Additionally, we’ve looked at alternatives for simpler use cases with Java’s disjoint() and Apache’s containsAny().
🌐
W3Docs
w3docs.com › java
Java List.contains(Object with field value equal to x)
To check if a Java List contains an object with a specific field value, you can use the List.stream().anyMatch() method along with a lambda expression to filter the elements in the list based on the field value.
Find elsewhere
🌐
Medium
medium.com › @Mohd_Aamir_17 › exploring-anymatch-and-findfirst-in-java-8-streams-with-examples-63a7c54d5e9f
Exploring anyMatch and findFirst in Java 8 Streams with Examples | by Mohd Aamir | Medium
September 5, 2024 - Predicate: A functional interface that represents a condition to be checked on elements of the stream. Returns: true if at least one element matches the predicate; false otherwise. Let’s take a simple example to check if a list of integers contains any even numbers. import java.util.Arrays; import java.util.List; public class AnyMatchExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 3, 5, 7, 10); boolean hasEven = numbers.stream() .anyMatch(n -> n % 2 == 0); System.out.println("Contains an even number: " + hasEven); } }
🌐
Baeldung
baeldung.com › home › java › java streams › introduction to java streams
Introduction to Java Streams | Baeldung
November 4, 2023 - One of the major new features in Java 8 is the introduction of the stream functionality – java.util.stream – which contains classes for processing sequences of elements.
🌐
Baeldung
baeldung.com › home › java › java list › check if a list contains a string element while ignoring case
Check if a List Contains a String Element While Ignoring Case | Baeldung
March 7, 2025 - In this quick tutorial, we’ll explore various methods and strategies to solve this common problem in Java. List provides the convenient contains() method to check if a given value exists in the list.
🌐
JRebel
jrebel.com › blog › java-streams-in-java-8
Using Java Streams in Java 8 and Beyond | JRebel by Perforce
Here are some common operations in Java streams. You won't use all of these functions every time you encounter a stream, but you have them available to use at will: Filter: Returns a new stream that contains some of the elements of the original. It accepts the predicate to compute which elements ...
🌐
Stackify
stackify.com › streams-guide-java-8
A Guide to Java Streams: In-Depth Tutorial With Examples
September 4, 2024 - This method can be used with streams of any type (Stream<T>, IntStream, LongStream, or DoubleStream). When applied, it creates a new stream that contains all elements from the first stream followed by all elements from the second stream.
🌐
Baeldung
baeldung.com › home › java › java list › how to find an element in a list with java
How to Find an Element in a List with Java | Baeldung
September 19, 2025 - Java itself provides several ways ... contains(Object element) As the name suggests, this method returns true if the list contains the specified element, and returns false otherwise....
🌐
Oracle
docs.oracle.com › en › java › javase › 15 › docs › api › java.base › java › util › stream › Stream.html
Stream (Java SE 15 & JDK 15)
Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-array-contains-value
How to Check if a Java Array Contains a Value? | DigitalOcean
September 16, 2025 - Java offers multiple ways to check if an array contains a specific value—each suited to different scenarios. The for-loop is the most universally compatible method and works with all types of arrays, including primitives. Java 8+ Streams bring modern, functional syntax that improves readability and integrates well with other Stream operations.
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › util › stream › Stream.html
Stream (Java SE 21 & JDK 21)
January 20, 2026 - Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › util › stream › Stream.html
Stream (Java SE 17 & JDK 17)
January 20, 2026 - Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.
🌐
GeeksforGeeks
geeksforgeeks.org › java › stream-filter-java-examples
Stream filter() in Java with examples - GeeksforGeeks
July 9, 2024 - // Java Program to Get Stream Consisting of Elements // of Stream that Matches Given Predicate // for Stream Filter (Predicate predicate) // Importing required classes import java.util.stream.Stream; // Class class GFG { // Main driver method public static void main(String[] args) { // Creating a stream of strings Stream<String> stream = Stream.of( "Geeks", "fOr", "GEEKSQUIZ", "GeeksforGeeks"); // Getting a stream consisting of the // elements having UpperCase Character // at custom index say be it '1' // using Stream filter(Predicate predicate) stream .filter( str -> Character.isUpperCase(str.charAt(1))) .forEach(System.out::println); } }