Description
Program to get value from HashMap when the key is provided.
Example
import java.util.HashMap; class HashMapDemo{ public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> hmap = new HashMap<Integer, String>(); //add elements to HashMap hmap.put(1, "AA"); hmap.put(2, "BB"); hmap.put(3, "CC"); hmap.put(4, "DD"); // Getting values from HashMap String val=hmap.get(4); System.out.println("The Value mapped to Key 4 is:"+ val); /* Here Key "5" is not mapped to any value so this * operation returns null. */ String val2=hmap.get(5); System.out.println("The Value mapped to Key 5 is:"+ val2); } }
Output:
The Value mapped to Key 4 is:DD The Value mapped to Key 5 is:null
Note: In the above program the key 5 is not mapped to any value so the get() method returned null, However you must not use this method for checking existence of a Key in HashMap because a return value of null does not necessarily indicate that the map contains no mapping for the key; it’s also possible that the map explicitly maps the key to null. You must use the containsKey() method for checking the existence of a Key in HashMap.
deepthi says
can you please tell me how to get all entries from HashMap or Map object.