printing elemenst in hashmap

Solutions on MaxInterview for printing elemenst in hashmap by the best coders in the world

showing results for - "printing elemenst in hashmap"
Luna
16 Aug 2020
1import java.util.HashMap;
2import java.util.Map;
3import java.util.Iterator;
4import java.util.Set;
5public class Details {
6
7   public static void main(String args[]) {
8
9      /* This is how to declare HashMap */
10      HashMap<Integer, String> hmap = new HashMap<Integer, String>();
11
12      /*Adding elements to HashMap*/
13      hmap.put(12, "Chaitanya");
14      hmap.put(2, "Rahul");
15      hmap.put(7, "Singh");
16      hmap.put(49, "Ajeet");
17      hmap.put(3, "Anuj");
18
19      /* Display content using Iterator*/
20      Set set = hmap.entrySet();
21      Iterator iterator = set.iterator();
22      while(iterator.hasNext()) {
23         Map.Entry mentry = (Map.Entry)iterator.next();
24         System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
25         System.out.println(mentry.getValue());
26      }
27
28      /* Get values based on key*/
29      String var= hmap.get(2);
30      System.out.println("Value at index 2 is: "+var);
31
32      /* Remove values based on key*/
33      hmap.remove(3);
34      System.out.println("Map key and values after removal:");
35      Set set2 = hmap.entrySet();
36      Iterator iterator2 = set2.iterator();
37      while(iterator2.hasNext()) {
38          Map.Entry mentry2 = (Map.Entry)iterator2.next();
39          System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
40          System.out.println(mentry2.getValue());
41       }
42
43   }
44}