1. 程式人生 > >Java HashMap遍歷的三種方式

Java HashMap遍歷的三種方式

public class TestHashMap {
    public static void main(String[] args) {


        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < 5; i++) {
            map.put(i + "", "value" + i);
        }
        //第一種方式:通過遍歷Map.keySet()遍歷HashMap的key和value
        firstMethod(map);

        //第二種方式:通過遍歷values()遍歷Map的value,但是不能遍歷key
secondMethod1(map); secondMethod2(map); //第三種方式:通過Map.entrySet()使用iterator()遍歷HashMap的key和value thirdMethod1(map); thirdMethod2(map); } private static void firstMethod(Map<String, String> map) { long startTime = System.currentTimeMillis(); System.out
.println("第一種方式:通過遍歷Map.keySet()遍歷HashMap的key和value"); for (String key : map.keySet()) { System.out.println("key= "+ key + " and value= " + map.get(key)); } System.out.println("第一種耗時:"+(System.currentTimeMillis() - startTime)); } private static void secondMethod1
(Map<String, String> map) { long startTime = System.currentTimeMillis(); startTime = System.currentTimeMillis(); System.out.println("第二種方式:通過遍歷values()遍歷Map的value,但是不能遍歷key"); Collection<String> values = map.values(); for(Iterator<String> it2 = values.iterator();it2.hasNext();){ it2.next(); } System.out.println("第二種耗時:"+(System.currentTimeMillis() - startTime)); } private static void secondMethod2(Map<String, String> map) { long startTime = System.currentTimeMillis(); startTime = System.currentTimeMillis(); System.out.println("第二種方式:通過遍歷values()遍歷Map的value,但是不能遍歷key"); for (String v : map.values()) { System.out.println("value= " + v); } System.out.println("第二種耗時:"+(System.currentTimeMillis() - startTime)); } private static void thirdMethod1(Map<String, String> map) { long startTime = System.currentTimeMillis(); startTime = System.currentTimeMillis(); System.out.println("第三種方式:通過Map.entrySet()使用iterator()遍歷HashMap的key和value"); Iterator<Map.Entry<String, String>> it3 = map.entrySet().iterator(); while(it3.hasNext()){ Map.Entry<String, String> entry = it3.next(); entry.getKey(); entry.getValue(); System.out.println("key:"+entry.getKey()+" value:"+entry.getValue()); } System.out.println("第三種耗時:"+(System.currentTimeMillis() - startTime)); } private static void thirdMethod2(Map<String, String> map) { long startTime = System.currentTimeMillis(); startTime = System.currentTimeMillis(); System.out.println("第三種方式:通過Map.entrySet()使用iterator()遍歷HashMap的key和value"); //map容量大時用此種遍歷方式 for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key: " + entry.getKey() + " and value: " + entry.getValue()); } System.out.println("第三種耗時:"+(System.currentTimeMillis() - startTime)); } }