How to check if a map contains an entry for a key in Java
In Java, we can use the containsKey method to check if a map contains a mapping value for a key.
Syntax
Map.containsKey(Object key);
This method returns true if the mapping for the key is present and false otherwise.
Code
import java.util.HashMap;class Main {public static void main(String[] args){// create a HashMapHashMap<Integer, String> numbers = new HashMap<>();// add mappings to the HashMapnumbers.put(1, "One");numbers.put(2, "Two");numbers.put(3, "Three");System.out.println("The numbers map is =>" + numbers );System.out.println("\nChecking if the key 1 is present in map =>" + numbers.containsKey(1));System.out.println("\nChecking if the key 4 is present in map =>" + numbers.containsKey(4));System.out.println("\nAdding a mapping for key '4'");numbers.put(4, "four");System.out.println("\nChecking if the key 4 is present in map =>" + numbers.containsKey(4));}}
Explanation
In the code above, we have:
-
Created a
Mapwith three values. -
Checked if the mapping is presently using the
containsKeymethod. For:key 1there is a mapping present, so thecontainsKeymethod will returntrue.key 4there is no mapping present, so thecontainsKeymethod will returnfalse.
-
Added mapping for
key-4and checked if a mapping forkey-4is present. Since it is, thecontainsKeymethod will now returntrue.