This post will discuss how to check if a value exists in a Map in Java. A value value exists in the map if it contains at least one mapping to a value v for which Objects.equals(value, v) holds.

1. Using containsValue() method

The standard solution to check if a value exists in a map is using the containsValue() method, which returns true if the map maps one or more keys to the specified value.

Download  Run Code

 
Note that if the value is an custom object, remember to override the equals and hashCode methods of that class.

2. Using anyMatch() method

The idea is to get the collection of the values contained in the map, and then search the specified value in that collection. This can be done in a single line using Stream API:

Download  Run Code

3. Using for loop

Before Java 8, you can write a custom routine to determine if a value exists in a Map or not. Here’s a working example:

Download  Run Code

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