w3resource

Java: Test if a map contains a mapping for the specified key


7. Check If Key Exists in Map

Write a Java program to test if a map contains a mapping for the specified key.

Sample Solution:-

Java Code:

import java.util.*;  
public class Example7 {  
   public static void main(String args[]) {
  HashMap < String, Integer > hash_map = new HashMap < String, Integer > ();
  hash_map.put("Red", 1);
  hash_map.put("Green", 2);
  hash_map.put("Black", 3);
  hash_map.put("White", 4);
  hash_map.put("Blue", 5);
  // print the map
  System.out.println("The Original map: " + hash_map);
  System.out.println("1. Is key 'Green' exists?");
  if (hash_map.containsKey("Green")) {
   //key exists
   System.out.println("yes! - " + hash_map.get("Green"));
  } else {
   //key does not exists
   System.out.println("no!");
  }

  System.out.println("\n2. Is key 'orange' exists?");
  if (hash_map.containsKey("orange")) {
   System.out.println("yes! - " + hash_map.get("orange"));
  } else {
   System.out.println("no!");
  }
 }
}

Sample Output:

The Original map: {Red=1, White=4, Blue=5, Black=3, Green=2}           
1. Is key 'Green' exists?                                              
yes! - 2                                                               
                                                                       
2. Is key 'orange' exists?                                             
no!
 

For more Practice: Solve these Related Problems:

  • Write a Java program to check if a HashMap contains a specific key using containsKey() and print a custom message.
  • Write a Java program to use Java streams to filter a map’s key set for a given key and return a boolean result.
  • Write a Java program to iterate over a map and manually check for the existence of a key, then print the result.
  • Write a Java program to implement a method that checks if a key is present in a map and returns its associated value if found.

Go to:


PREV : Get Shallow Copy of HashMap.
NEXT : Check If Value Exists in Map.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.