遍历HashMap的四种方式
package com.oracle.containers.map; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * @author zhouyanxiang * @create 2020-08-2020/8/17-10:13 */ public class HashMapReview { public static void main(String[] args) { HashMap <String,String> map = new HashMap<>(); map.put("Tom","23"); map.put("Jerry","24"); map.put("Mike","29"); map.put("Mary","22"); map.put("Bruce","20"); map.put("Jerry","24"); // 如果有相同的并不会算进map.size里面去 System.out.println(map.size()); // 遍历HashMap的四种方式 System.out.println("====== No1 ======"); // 第一种 通过Map.keySet遍历key和value System.out.println("通过Map.keySet遍历key和value"); for (Object key:map.keySet()){ System.out.println("key : " + key + " value: " + map.get(key)); } System.out.println("====== No2 ======"); // 第二种 System.out.println("通过Map.entrySet使用iterator遍历key和value"); Iterator it = map.entrySet().iterator(); while (it.hasNext()){ Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next(); System.out.println("key : " + entry.getKey() + " value: " + entry.getValue()); } System.out.println("====== No3 ======"); // 第三种 推荐,尤其是容量大时 通过Map.entrySet遍历key和value System.out.println("通过Map.entrySet遍历key和value"); for (Map.Entry<String, String> entry : map.entrySet()){ System.out.println("key : " + entry.getKey() + " value: " + entry.getValue()); } System.out.println("====== No4 ======"); System.out.println("通过Map.values()遍历所有的value,但不能遍历key"); for(String v:map.values()) { System.out.println("value: " + v); } } }
输出如下: