Java Map常用的遍历方法

public static void main(String[] args) {
        Map<String,Object> map = new HashMap<>();
        map.put("1","6");
        map.put("2","7");
        map.put("3","8");
        map.put("4","9");
        map.put("5","0");
        //方法一:entrySet()迭代
        Iterator<Map.Entry<String,Object>> it = map.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry<String,Object> entry = it.next();
            System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
        }
        //方法二:entrySet() forEach循环(最常用)
        for(Map.Entry<String,Object> entry : map.entrySet()){
            System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
        }
        //方法三:keySet() 先获取key再获取value
        for(String key : map.keySet()){
            System.out.println("key:" + key + ",value:" + map.get(key));
        }
        //方法四:key和value分别遍历
        for(String key : map.keySet()){
            System.out.println("key:" + key);
        }
        for(Object value : map.values()) {
            System.out.println("value:" + value);
        }
    }

猜你喜欢

转载自blog.csdn.net/pyy542718473/article/details/103820977