遍历Map集合中所有元素,三种方式

(1)先获得Map集合中所有的键,遍历键的集合,去挨个获取键对应的值

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);
        }
    }
}

在这里插入图片描述
(2)先获取Map集合中的所有键值对,再遍历每一个键值对,从键值对中分别得出键和值。

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);
        }
    }
}

在这里插入图片描述
(3)通过values方法获取Map集合中的所有值的集合

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);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44255741/article/details/128523331