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
66
67
68
69
70
71
72
73
| /*
HashMap
LinkedHashMap 可以按insert order或者access order排序
TreeMap 根据key来排序
1.clear() 清除
2.containsKey(key: Object)
3.containsValue(value: Object)
4.entrySet(): Set<Map.Entry<K, V>> 返回一个包含map中条目的set
5.get(key: Object): v
6.isEmpty()
7.put(key: K, value: V): V
8.putAll(m: Map<? extends K,? extends V>)
9.remove(key: object)
10.size()
11.values(): Collection<V>
*/
public class Student{
public String name;
public int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", score=" + score +
'}';
}
public static void main(String[] args) {
//HashMap无序
//Map<String, Integer> map = new HashMap<>();
//TreeMap有序, 指定排序规则
Map<Student, Integer> map = new TreeMap<>(new Comparator<Student>() {
public int compare(Student o1, Student o2) {
if (o1.score == o2.score){
return 0;
}
return o1.score > o2.score ? -1: 1;
}
});
map.put(new Student("wk", 12), 1);
map.put(new Student("test", 123), 2);
//遍历key
for(Student key: map.keySet()){
Integer value = map.get(key);
System.out.println();
}
//遍历value
for(Integer value: map.values()){
System.out.println(value);
}
//遍历entry,效率较高,比遍历key后获取value
for(Map.Entry<Student, Integer> entry: map.entrySet()){
Student key = entry.getKey();
Integer value = entry.getValue();
}
//使用Iterator遍历
Iterator<Map.Entry<Student, Integer>> entities = map.entrySet().iterator();
while (entities.hasNext()){
Map.Entry<Student, Integer> entry = entities.next();
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
|