Traverse all elements in the Map collection, three ways

(1) First obtain all the keys in the Map collection, traverse the collection of keys, and obtain the values ​​corresponding to the keys one by one

public class Example {
    
    
    public static void main(String[] args) {
    
    
        Map map= new HashMap();
        map.put("一","Jack");
        map.put("二","Rose");
        map.put("三","Lucy");
        Set keyset=map.keySet();//获得所有键
        Iterator it = keyset.iterator();
        while (it.hasNext()) {
    
    //遍历每一个键,由键获得值
            Object key = it.next();
            Object value = map.get(key);
            System.out.println(key+":"+value);
        }
    }
}

insert image description here
(2) First obtain all the key-value pairs in the Map collection, then traverse each key-value pair, and obtain the key and value from the key-value pair.

public class Example {
    
    
    public static void main(String[] args) {
    
    
        Map map= new HashMap();
        map.put("一","Jack");
        map.put("二","Rose");
        map.put("三","Lucy");
        Set entryset=map.entrySet();//获得所有键-值对
        Iterator it = entryset.iterator();
        while (it.hasNext()) {
    
    
            Map.Entry entry = (Map.Entry) it.next();
            Object key =  entry.getKey();
            Object value = entry.getValue();
            System.out.println(key+":"+value);
        }
    }
}

insert image description here
(3) Obtain the collection of all values ​​in the Map collection through the values ​​method

public class Example {
    
    
    public static void main(String[] args) {
    
    
        Map map= new HashMap();
        map.put("一","Jack");
        map.put("二","Rose");
        map.put("三","Lucy");
        map.put("四","Tom");
        Collection values =map.values();
        Iterator it = values.iterator();
        while (it.hasNext()) {
    
    
            Object value = it.next();
            System.out.println(value);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_44255741/article/details/128523331