-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMapExample.java
More file actions
65 lines (56 loc) · 2.04 KB
/
HashMapExample.java
File metadata and controls
65 lines (56 loc) · 2.04 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapExample {
public static void main(String[] args) {
// HashMap is used for unordered data collection
Map<String, String> map = new HashMap<>();
map.put("Bihar", "Patna");
map.put("Jharkhand", "Ranchi");
map.put("UP", "Lucknow");
System.out.println(map);
/*
Map is like key value pairs just as json in JS
*/
map.put("Karnataka", "Bengaluru");
System.out.println(map);
/*
The order of the items in the hashmap is not guaranteed
that is why it is suitable for unordered data collection
whereas with tha arrayList we have got the data in the
order as we have added them to the list
*/
// Getting an item form Hashmap
String cap = map.get("Bihar");
System.out.println("Capital of Bihar is "+cap);
// Removing an item from the Hashmap
map.remove("Karnataka");
System.out.println(map);
/*
While removing we provide the key of the data pair to be removed
and the key and the data both are gone as we can see
*/
/*
We can get a set of keys that are there in the hashMap
which guarantees uniques values that we can't get with
arrayList
*/
Set<String> keySet = map.keySet();
System.out.println("Key set is "+keySet);
/*
We can get the data from the hashmap that we have
created using the newly created keySet here,
using an iterator
*/
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()){
String key = iterator.next();
System.out.println("The capital of "+key+" is "+map.get(key));
}
// Getting data from the hashmap using forEach loop
for (String key : keySet){
System.out.println("The capital of "+key+" is "+map.get(key));
}
}
}