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("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!
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Get a shallow copy of a HashMap instance.
Next: Test if a map contains a mapping for the specified value.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework