Wednesday, May 10, 2023

Java HashMap ContainsKey and ContainsValue Example - How to check if a Key Exists in Map?

Hello guys, one of the common problems many Java developers working with HashMap face is how to check if the Map contains a particular key or value? You can use this to check duplicate keys or just to ensure that you are not overriding the current value because if you insert a key that already exists in the HashMap, then you end up overriding its value. Since HashMap also allows duplicate values, it's also possible that the same value may be paired against multiple keys, so just removing a mapping may not be enough to remove that particular value. Not paying attention to these details has actually caused issues in the Java applications.

In order to safeguard against these kinds of the situation or simply just to check if a particular key or value exists in the HashMap, you can use the containsKey() and containsValue() method from the HashMap class in Java.

Both these method takes a Key or Value object and return a boolean, i.e. true if key or value exists in the Map or false if it didn't.

While doing code reviews I have seen many Java developers like to iterate over the map to check if a particular key or value exists in the HashMap or not, that's not ideal and takes more time; instead, you should use the containsKey() and containsValue() method to solve the problem.

That's why it's important for a Java developer to know the Java API well. If you know the Java API better then you can solve your day-to-day Java problem in simpler and performant ways.




Java HashMap containsKey() and containsValue() Example

Now, let's see a simple example to understand how you can check if a particular key or value exists in the HashMap or not. In this program, I have created a Map that holds it to name mapping of employees. It's a small map and just contains five entries, but that's enough to understand how to use containsKey() and containsValue() methods.

Here is the structure of the HashMap class, you can see how entries are stored and how the lookup happens. If you want to learn more, you also check out How HashMap works in Java article from this blog.
Java HashMap ContainsKey and ContainsValue Example - Check if a Key or Value exists in the Map


Anyway, without wasting any more of your time, here is the complete Java code to check if a key or value exists in a given Map or not.

package tool;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * 
 * A simple Java Program to check if HashMap contains a given key or value or not
 * in Java.
 */
public class ContainsKeyExample {
 
  public static void main(String[] args) {
 
    // let's create a Map which maps id to name
    Map<Integer, String> idToName = new HashMap<>();
 
    idToName.put(100, "James");
    idToName.put(101, "Jack");
    idToName.put(102, "Jasmin");
    idToName.put(103, "Joe");
    idToName.put(104, "Joshua");
 
    // now let's check if a key or Id 200 is present in Map
    boolean isId200Exists = idToName.containsKey(200);
    boolean isId100Exists = idToName.containsKey(100);
 
    System.out.println("Is key 200 exists in the map? " + isId200Exists);
    System.out.println("Is key 100 exists in the Hashmap? " + isId100Exists);
 
    // now let's check if a value or name is present in Map
    boolean isJimmyExists = idToName.containsValue("Jimmy");
    boolean isJoeExists = idToName.containsValue("Joe");
 
    System.out.println("Is value Jimmy exists in the map? " + isJimmyExists);
    System.out.println("Is value Joe exists in the Hashmap? " + isJoeExists);
 
  }
 
}
 
Output
Is key 200 exists in the map? false
Is key 100 exists in the Hashmap? true
Is value Jimmy exists in the map? false
Is value Joe exists in the Hashmap? true

As you can see that when we search for a non-existent key, 200 the containsKey() method returned false and when we search for an existing key like 100 it returned true.  Similarly, the containsValue() method returns false when you search for a non-existent value but returns true if the value is present in the Map.

That's what we wanted, mission accomplished. Though, if you want to learn more about the HashMap class or Java Collection Framework itself then you can also check out these 10 Examples of HashMap in Java tutorial where I have shared how to create an HashMap, update keys and values on HashMap, retrieve values using Keys, remove a particular key and value, and how to iterate over HashMap and process keys in order. 




Important Points about containsKey() and containsValue()

1. Both containsKey() and containsValue() methods are defined in java.util.Map interface which means they are available not just to HashMap but to all kinds of Maps, like the TreeMap, LinkedHashMap, Hashtable, and ConcurrentHashMap in Java.

2. The containsKey() method returns true if a given key is present in the Map precisely if the following condition is true:

key==null ? k==null : key.equals(k)

This means if Map permits null key and you pass null, then containsKey may return true.

Also, knowing Java API helps and that's why it's recommended for Java developers to learn the API better. This is also one of the numerous helpful pieces of advice given by Joshua Bloch in his classic, must-read Effective Java book. If you haven't read it, I strongly suggest you read it once. It will make you a better Java developer.

best book for advanced Java programmers



3. The containsKey() method may throw NullPointerException if Map doesn't support null keys, like Hashtable. It can also throw ClassCastException if the type of given key is not compatible with the keys in the Map.

4. The containsValue() method returns true if the Map contains the given value, I mean at least contains one such mapping where the value matches the given value. Precisely when the following condition is true:

value==null ? v==null : value.equals(v)

5. The containsValue() may require time linear in the map size for most of the Map interface implementation because it needs to traverse through Map to get the value.

6. Similar to containsKey(), the containsValue() method can also throw ClassCastException for incompatible values and NullPointerException if the value is null and that Map implementation doesn't support null values, like Hashtable.


That's all about how to check if a given key or value exists in the HashMap in Java or not. As we have learned, you can use the containsKey() and containsValue() method to check for the existent of any key or value. These methods are also declared in the Map interface, which means you can use these methods with any Map implementations, like to check keys and values in the TreeMap, LinkedHashMap, Hashtable, and ConcurrentHashMap.



Related Java Collections Tutorials
If you are interested in learning more about Java Collections Framework or HashMap itself then you may like to see the following articles
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to use filter() method in Java 8 (tutorial)
  • How to convert List to Map in Java 8 (solution)
  • Difference between abstract class and interface in Java 8? (answer)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to use peek() method in Java 8 (example)
  • Difference between HashSet, TreeSet, and LinkedHashSet in Java? (answer)
  • Difference between HashMap and ArrayList in Java? (answer)
  • Difference between HashSet and ArrayList in Java? (answer)
  • 5 differences between HashMap and Hashtable in Java? (answer)
  • What is the difference between ArrayList and LinkedList in Java? (answer)
  • How to use NavigableMap in Java 6? [example]
  • How to use BlockingQueue in Java Program? [example]
  • Top 5 Courses to learn Java Collections Framework in-depth (courses)
  • How to sort the map by keys in Java 8? (example)
  • How to sort the may by values in Java 8? (example)
  • Top 10 Advanced Core Java courses for experienced Programmers (courses)
Thanks for reading this article so far. If you like this Java HashMap tutorial and tips, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.


P.S. - If you are new to the Java world and want to learn Java from scratch but looking for a free book or online course then I also suggest you check out Practice Java by Building Projects, a hands-on, and a free course on Udemy. All you need to do is create a free Udemy account and enroll in this course. 

1 comment :

Anonymous said...

Is there a better way to check if a key exists in HashMap?

Post a Comment