Home HashMap的四种遍历方法
Post
Cancel

HashMap的四种遍历方法

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
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class MapShowTest {
    public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < 10; i++) {
            map.put(i, i + 1);
        }

        // 通过Map.keySet遍历key和value
        for (int temp : map.keySet()) {
            System.out.print(temp + "=" + map.get(temp) + ", ");
        }

        // 通过Map.entrySet遍历key和value,推荐,尤其是容量大时
        Set<Map.Entry<Integer, Integer>> entry = map.entrySet();
        for (Map.Entry<Integer, Integer> temp : entry) {
            System.out.print(temp.getKey() + "=" + temp.getValue() + ", ");
        }

        // 通过Map.entrySet使用iterator遍历key和value
        Set<Map.Entry<Integer, Integer>> entry1 = map.entrySet();
        Iterator<Entry<Integer, Integer>> iterator = entry1.iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, Integer> mapTemp = iterator.next();
            System.out.print(mapTemp.getKey() + "=" + mapTemp.getValue() + ", ");
        }

        //通过Map.values()遍历所有的value,但不能遍历key
        Collection<Integer> c = map.values();
        for (int temp : c) {
            System.out.print("value= " + temp + ", ");
        }
    }
}
This post is licensed under CC BY 4.0 by the author.