forked from Bhagabat/JavaExamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashmapIterateEx.java
More file actions
55 lines (45 loc) · 1.58 KB
/
HashmapIterateEx.java
File metadata and controls
55 lines (45 loc) · 1.58 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
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/*
* Author: Edwin Torres
* email: CoachEd@gmail.com
*
* This example shows different ways to iterate through a HashMap
*/
public class HashmapIterateEx {
public static void main(String[] args) {
/** create a HashMap and populate it with some values */
HashMap<String,String> hm = new HashMap<String,String>();
hm.put("Carmelo","New York Knicks");
hm.put("Dwight","Houston Rockets");
hm.put("Kobe","Los Angeles Lakers");
hm.put("Derrick","Chicago Bulls");
String key, val;
/** for each method */
for (Map.Entry<String,String> entry : hm.entrySet()) {
key = entry.getKey();
val = entry.getValue();
System.out.println(key + " , " + val);
}
System.out.println();
/** iterate over keys */
Iterator<String> iter1 = hm.keySet().iterator();
while (iter1.hasNext()) {
key = iter1.next();
val = hm.get(key);
System.out.println(key + " , " + val);
}
System.out.println();
/** iterate over values */
Map.Entry<String,String> entry;
Iterator<Map.Entry<String,String>> iter2 = hm.entrySet().iterator();
while (iter2.hasNext()) {
entry = iter2.next();
key = entry.getKey();
val = entry.getValue();
System.out.println(key + " , " + val);
}
System.out.println();
}
}