Map集合遍历的两种方式

   public static void main(String[] args) {
        Map<String,String> map = new HashMap<String,String>();

        map.put("黄海燕","何沁秋");
        map.put("马月平","麻将");
        map.put("杨悦","李阳");

方法一:根据KeySet方法获取主键集合,然后根据主键找到对应的值进行遍历

Set<String> keySet = map.keySet();
//        for(String i :keySet){
//            String value = map.get(i);
//            System.out.println(i+","+value);
//        }

方式2:根据entrySet()方法获取map,创建set集合对象,然后根据集合对象获取对应的主键和值

Set<Map.Entry<String, String>> entrySet = map.entrySet();
        for (Map.Entry<String, String> me:entrySet){
            String key = me.getKey();
            String value = me.getValue();
            System.out.println(key+","+value);
        }

评论

暂无评论