标签:color entry stat asn value hashmap get nbsp main
第一种:
public static void main(String[] args) { //遍历Map 第一种方式 Map<String, Integer> map1 = new HashMap<String, Integer>(); map1.put("jack", 20); map1.put("rose", 18); map1.put("lucy", 17); map1.put("java", 25); //通过 map1.keySet() 获取key 通过key 找到value for (String key : map1.keySet()) { Integer value = map1.get(key); System.out.println("key : "+key+" value : "+value); } }
第二种:
public static void main(String[] args) { //遍历Map 第二种方式 Map<String, Integer> map1 = new HashMap<String, Integer>(); map1.put("jack", 20); map1.put("rose", 18); map1.put("lucy", 17); map1.put("java", 25); //通过Map.Entry(String,Integer) 获取,然后使用entry.getKey()获取到键,通过entry.getValue()获取到值 for(Map.Entry<String, Integer> entry : map1.entrySet()){ System.out.println("键 key :"+entry.getKey()+" 值value :"+entry.getValue()); } }
第三种:
复制代码 //遍历Map 第三种方式 Map<String, Integer> map1 = new HashMap<String, Integer>(); map1.put("jack", 20); map1.put("rose", 18); map1.put("lucy", 17); map1.put("java", 25); //第三种只遍历键或者值,通过加强for循环 for(String s1:map1.keySet()){//遍历map的键 System.out.println("键key :"+s1); } for(Integer s2:map1.values()){//遍历map的值 System.out.println("值value :"+s2); } System.out.println("===================================="); }
第四种:
public static void main(String[] args) { //遍历Map 第一种方式 Map<String, Integer> map1 = new HashMap<String, Integer>(); map1.put("jack", 20); map1.put("rose", 18); map1.put("lucy", 17); map1.put("java", 25); //第四种Iterator遍历获取,然后获取到Map.Entry<String, String>,再得到getKey()和getValue() Iterator<Map.Entry<String, Integer>> it=map1.entrySet().iterator(); while(it.hasNext()){ Map.Entry<String, Integer> entry=it.next(); System.out.println("键key :"+entry.getKey()+" value :"+entry.getValue()); } }
标签:color entry stat asn value hashmap get nbsp main
原文地址:https://www.cnblogs.com/Yusco/p/12286979.html