Java Collection, HashMap Exercises: Test if a map contains a mapping for the specified key

Java Collection, HashMap Exercises: Exercise-7 with Solution

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("\n2. Is key 'orange' exists?");
  if (hash_map.containsKey("orange")) {
   System.out.println("yes! - " + hash_map.get("orange"));
  } else {

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?                                             

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Java: Tips of the Day

Try and catch:

Java is excellent at catching errors, but it can only recover gracefully if you tell it what to do. The cascading hierarchy of attempting to perform an action in Java starts with try, falls back to catch, and ends with finally. Should the try clause fail, then catch is invoked, and in the end, there's always finally to perform some sensible action regardless of the results. Here's an example:

try {
        cmd = parser.parse(opt, args); 
        if(cmd.hasOption("help")) {
                HelpFormatter helper = new HelpFormatter();
                helper.printHelp("Hello ", opt);
        else {
                if(cmd.hasOption("shell") || cmd.hasOption("s")) {
                String target = cmd.getOptionValue("tgt");
                } // else
        } // fi
} catch (ParseException err) {
        } //catch
        finally {
                new Hello().helloWorld(opt);
        } //finally
} //try

It's a robust system that attempts to avoid irrecoverable errors or, at least, to provide you with the option to give useful feedback to the user. Use it often, and your users will thank you!

Ref: https://red.ht/3EZc9OC