Check if a value exists in a Map in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<Character, Integer> hashMap = new HashMap<>(); for (int i = 65; i <= 90; i++) { hashMap.put((char) i, i); } int value = 70; boolean isExists = hashMap.containsValue(value); System.out.println(isExists); // true } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<Character, Integer> hashMap = new HashMap<>(); for (int i = 65; i <= 90; i++) { hashMap.put((char) i, i); } int value = 70; boolean isExists = hashMap.values().stream().anyMatch(v -> v == value); System.out.println(isExists); // true } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<Character, Integer> hashMap = new HashMap<>(); for (int i = 65; i <= 90; i++) { hashMap.put((char) i, i); } int value = 70; boolean isExists = false; for (Integer v: hashMap.values()) { if (v == value) { isExists = true; break; } } System.out.println(isExists); // true } } |
That’s all about checking if a value exists in a Map in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)