This post will discuss how to check if a value exists in a List in Java.

1. Using List.contains() method

To check whether a List contains a given element or not, you can simply use the List.contains() method as demonstrated below:

Download  Run Code

 
You might want to override the equals() and hashCode() methods to make this work correctly with objects. Please note that the contains() method might end up iterating the complete list to find a value. For frequent calls, it’s better to convert the list into a set and call the contains() method on it.

Download  Run Code

2. Using Stream.filter() method

This can be easily done using Java 8 Stream filters. Here’s the code demonstrating the usage:

Download  Run Code

 
Here’s an even shorter version of the above code that makes use of the anyMatch() method to conditionally search an element in a List:

Download  Run Code

3. Using Apache Commons Collections

You can also use CollectionUtils.containsAny() provided by Apache Commons Collections that works in a similar way as Collections.contains() method.

Download Code

4. Using enhanced for loop

If you use Java 7 or less, you can conditionally search for an element in the List using an enhanced for loop.

Download  Run Code

That’s all about checking if a value exists in a List in Java.