HashMap四种遍历

	public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("1", "tom");
        map.put("2", "jerry");
        map.put("3", "john");

        //第一种:通过keySet遍历
        for (String key : map.keySet()) {
            System.out.println(key + ": " + map.get(key));
        }

        //第二种:通过entrySet的Iterator
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        //第三种:通过entrySet遍历,大量数据时效率高
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        //第四种:遍历所有value,不能遍历key
        for (String val : map.values()) {
            System.out.println("value: " + val);
        }
    }

你可能感兴趣的:(Java)