1Map<String, String> myMap = new HashMap<String, String>() {{
2 put("a", "b");
3 put("c", "d");
4 }};
1// Import the HashMap class
2import java.util.HashMap;
3
4 // First Example
5 // Create a HashMap object called capitalCities
6 HashMap<String, String> capitalCities = new HashMap<String, String>();
7
8 // Add keys and values (Country, City)
9 capitalCities.put("England", "London");
10 capitalCities.put("Germany", "Berlin");
11 capitalCities.put("Norway", "Oslo");
12 capitalCities.put("USA", "Washington DC");
13 System.out.println(capitalCities);
14
15 //Second Example
16 // Create a HashMap object called stGrade
17 Map<String, Integer> stGrade = new HashMap<String, Integer>();
18
19 // Insert elements
20 stGrade.put("aaron", new Integer(90));
21 stGrade.put("isaac", new Integer(100));
22 stGrade.put("john", new Integer(35));
23 stGrade.put("mohammad", new Integer(100));
24
25 // Get value
26 stGrade.get("mohammad"); // returns 100
27 stGrade.get("aaron"); // returns 90
28 stGrade.get("john"); // returns 35
29 stGrade.get("isaac"); // returns 100
30
1//remember to first import java.util.*; first
2
3//you can swap out string or integer for other data types
4Map<String, Integer> d = new HashMap<>();
5
1//Hash map creation
2Map< String,Integer> hm =
3 new HashMap< String,Integer>();
4//inserting elements into hashmap
5 hm.put("a", new Integer(100));
6 hm.put("b", new Integer(200));
7 hm.put("c", new Integer(300));
8 hm.put("d", new Integer(400));
1HashMap<Integer,String> map=new HashMap<Integer,String>();//key is integer, value is String