HashMap的四种遍历方式

package cn.wyu.test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Test01 {

    public static void main(String[] args) {
        Map hashMap = new HashMap<>();
        hashMap.put("1", "value1");
        hashMap.put("2", "value2");
        hashMap.put("3", "value3");
        hashMap.put("4", "value4");
        hashMap.put("5", "value5");
        function01(hashMap);
        function02(hashMap);
        function03(hashMap);
        function04(hashMap);
    }


    //第一种:普遍使用,二次取值
    private static void function01(Map hashMap) {
        //hashMap.keySet是用来获取键的集合
        System.out.println("通过hashMap.keySet遍历key和value:");
        for (String key :hashMap.keySet()) {
            System.out.println(key+":"+hashMap.get(key));
        }
    }

    private static void function02(Map hashMap) {
        //第二种:hashMap.entrySet()返回键值对的Set集合,里面的每个对象表示Map的一个键值对
        System.out.println("通过hashMap.entrySet使用iterator遍历key和value:");
        Iterator> it = hashMap.entrySet().iterator();
        while (it.hasNext()) {
            //每个Map.Entry对象代表Map中的一个键值对
            Map.Entry entry = it.next();
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }
    }

    private static void function03(Map hashMap) {
        //第三种:推荐,尤其是容量大时
        System.out.println("通过hashMap.entrySet遍历key和value");
        for (Map.Entry entry : hashMap.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }
    }
    private static void function04(Map hashMap) {
        //第四种:hashMap.values()获取Map中存储所有的Collection集合
        System.out.println("通过hashMap.values()遍历所有的value,但不能遍历key");
        for (String v : hashMap.values()) {
            System.out.println("value= " + v);
        }
    }

}
通过hashMap.keySet遍历key和value:
1:value1
2:value2
3:value3
4:value4
5:value5
通过hashMap.entrySet使用iterator遍历key和value:
key= 1 and value= value1
key= 2 and value= value2
key= 3 and value= value3
key= 4 and value= value4
key= 5 and value= value5
通过hashMap.entrySet遍历key和value
key= 1 and value= value1
key= 2 and value= value2
key= 3 and value= value3
key= 4 and value= value4
key= 5 and value= value5
通过hashMap.values()遍历所有的value,但不能遍历key
value= value1
value= value2
value= value3
value= value4
value= value5

 

你可能感兴趣的:(JavaSE)