HashMap遍历

package com.huawei.scp.api.query;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

// HashMap的遍历有两种常用的方法,使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的。
public class TestHashMap
{
    public static void main(String[] args)
    {
        Map<String, Integer> map1 = new HashMap<String, Integer>();
        map1.put("a", 0);
        map1.put("b", 1);
        map1.put("c", 2);
        // keyset遍历
        System.out.println("keyset遍历-----------");
        for (String key : map1.keySet())
        {
            Integer value = map1.get(key);
            System.out.println("key:" + key + " value:" + value);
        }
        // entryset遍历
        System.out.println("\nentryset遍历-----------");
        for (Entry<String, Integer> entry : map1.entrySet())
        {
            String key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println("key:" + key + " value:" + value);
        }

        // 两者性能测试
        System.out.println("\n两者性能区别-----------");
        Map<String, Integer> map2 = new HashMap<String, Integer>();
        for (int i = 0; i < 99999; i++)
        {
            map2.put(String.valueOf(i), i);
        }

        // keyset遍历时间
        long time1Start = System.currentTimeMillis();
        for (String key : map2.keySet())
        {
            Integer value = map2.get(key);
            // System.out.println("key:" + key + " value:" + value);
        }
        long time1End = System.currentTimeMillis();
        System.out.println("keyset遍历需要时间:" + (time1End - time1Start));

        // entryset遍历时间
        long time2Start = System.currentTimeMillis();
        for (Entry<String, Integer> entry : map2.entrySet())
        {
            String key = entry.getKey();
            Integer value = entry.getValue();
            // System.out.println("key:" + key + " value:" + value);
        }
        long time2End = System.currentTimeMillis();
        System.out.println("entryset遍历需要时间:" + (time2End - time2Start));
    }
}

输出结果:

keyset遍历-----------
key:b value:1
key:c value:2
key:a value:0

entryset遍历-----------
key:b value:1
key:c value:2
key:a value:0

两者性能区别-----------
keyset遍历需要时间:16
entryset遍历需要时间:0


你可能感兴趣的:(算法,java编程思想,java编程思想,java经典书籍,java经典算法)