-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathASimpleMap.java
More file actions
63 lines (53 loc) · 2.12 KB
/
ASimpleMap.java
File metadata and controls
63 lines (53 loc) · 2.12 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
// HUK-SimpleMap/ASimpleMap.java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class ASimpleMap {
public static void main(String[] args) {
Map<String,Integer> map = new TreeMap<>();
map.put("Sue",167);
map.put("Ann",173);
map.put("Lea",170);
map.put("Kim",173);
Iterator<String> iter = map.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
int val = map.get(key); // auto(un)boxing
System.out.print(key + ": " + val + " ");
if (val == 170) iter.remove();
}
System.out.print("\nWe can print a map: " + map);
// returns null, or the value if present
map.putIfAbsent("Lea",169);
// returns old value or null if not present
map.replace("Lea",170);
System.out.print("\nIs there a key 'Lea'? " +
map.containsKey("Lea"));
System.out.print("\nIs there a key 'Zoe'? " +
map.containsKey("Zoe"));
// inefficient!
System.out.println("\nIs any girl 170 cm tall? " +
map.containsValue(170));
Integer was = map.remove("Ann");
if (was != null)
System.out.println("Ann removed, she was " +
was + " cm tall");
was = map.remove("Zoe");
if (was == null)
System.out.println("There was no 'Zoe'!");
System.out.println("getOrDefault: 'Zoe'->" +
map.getOrDefault("Zoe",-1));
System.out.println("getOrDefault: 'Lea'->" +
map.getOrDefault("Lea",-1));
System.out.print("Iterating over 'keySet': ");
for (String s : map.keySet())
System.out.print(s + "->" + map.get(s) +" ");
System.out.print("\nMore efficient way: ");
for (Map.Entry<String,Integer> e : map.entrySet())
System.out.print(e.getKey() + "->" +
e.getValue() + " ");
System.out.println();
}
}