map的5种遍历

//方式一(遍历key和value)
public <K, V> void test1(Map<K, V> map) {
    for (Map.Entry<K, V> entry : map.entrySet()) {
        System.out.print(entry.getKey() + "------");
        System.out.print(entry.getValue() + "    ");
    }
}

//方式二(遍历value)
public <K, V> void test2(Map<K, V> map) {
    for (K key : map.keySet()) {
        System.out.print(map.get(key) + "------");
    }
}

//方式三(遍历key和value)
public <K, V> void test3(Map<K, V> map) {
    SetK, V>> entries = map.entrySet();
    for (Map.Entry<K, V> entry : entries) {
        System.out.print(entry.getKey() + "--------" + entry.getValue() + "    ");
    }

}

//方式四(遍历key和value)
public <K, V> void test4(Map<K, V> map) {
    IteratorK, V>> iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<K, V> entry = iterator.next();
        System.out.print(entry.getKey() + "-------" + entry.getValue() + "     ");
    }
}

//方式5(遍历key和value)
public <K, V> void test5(Map<K, V> map) {
    for (Iterator i = map.entrySet().iterator(); i.hasNext(); ) {
        System.out.print(i.next() + "    ");
    }
}

你可能感兴趣的:(代码)