Java traverse the four ways Map collection

Map There are two sets of values, the set of values ​​can traverse Thus only traversed and to be traversed only the key set may be traversed simultaneously. Map and an interface (such as HashMap, TreeMap, LinkedHashMap, Hashtable, etc.) can traverse Map implementation in the following ways.

1. Use the for loop traversal Map of entries (the most common and most commonly used).

public static void main(String[] args) {
    Map<String, String> map = new HashMap<String, String>();
    map.put("Java", "http://www.baidu.com/java/");
    map.put("C语言入", "http://www.baidu.com/c/");
    for (Map.Entry<String, String> entry : map.entrySet()) {
        String mapKey = entry.getKey();
        String mapValue = entry.getValue();
        System.out.println(mapKey + ":" + mapValue);
    }
}

2. Use for-each loop traversal or key values, generally need only be applied during the Map value or key. The performance is better than entrySet.

Map<String, String> map = new HashMap<String, String>();
map.put("Java", "http://www.baidu.com/java/");
map.put("C语言", "http://www.baidu.com/c/");
// 打印键集合
for (String key : map.keySet()) {
    System.out.println(key);
}
// 打印值集合
for (String value : map.values()) {
    System.out.println(value);
}

3. Iterators (the Iterator) traversal

Map<String, String> map = new HashMap<String, String>();
map.put("Java", "http://www.baidu.com/java/");
map.put("C语言", "http://www.baidu.com/c/");
Iterator<Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Entry<String, String> entry = entries.next();
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key + ":" + value);
}

4. Traverse through the key value to find, in this way the efficiency is relatively low, because the operation itself is time-consuming from the key value.

for(String key : map.keySet()){
    String value = map.get(key);
    System.out.println(key+":"+value);
}
Published 457 original articles · won praise 94 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104715014