What is Map
Map is an Interface.In map data is stored in key-value format.
A map can not contain duplicate Key.We use map if we want to store,update and fetch data on the basis of key.
For Example:
-A map of country and capital
-A map of cities and zip code
-A map of environment variable and their value.
In the below code I am using Hashmap class which implements map interface to store and fetch country name and their capital .
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package selenium; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class MapCode { public static void main(String[] args) { Map<String,String> map=new HashMap<String,String>(); //Add data to hash map map.put("India", "New Delhi"); map.put("Switzerland","Bern"); map.put("Mexico", "Mexico City"); map.put("France","Paris"); //Print all the data for(Entry<String, String> entry:map.entrySet()) { System.out.println("Country name- "+entry.getKey() +" Capital name- " +entry.getValue()); } //Get value of a key System.out.println(map.get("Mexico")); //Verify a key is present or not in the map if(map.containsKey("Mexico")) { System.out.println("Key is present in Map"); }else { System.out.println("Key is not present in map"); } //To get the size of map System.out.println("Size of map is - "+map.size()); //Remove a key map.remove("Mexico"); //Print all the keys present in map Set<String> set=map.keySet(); for(String key:set) { System.out.println(key); } } } |
Output
1 2 3 4 5 6 7 8 9 10 |
Country name- Mexico Capital name- Mexico City Country name- France Capital name- Paris Country name- Switzerland Capital name- Bern Country name- India Capital name- New Delhi Mexico City Key is present in Map Size of map is - 4 France Switzerland India |