1 package com.renjy.test.cn; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map; 6 7 public class TestDriver { 8 public static void main(String args[]) { 9 Map<String, String> person = new HashMap<String, String>(); 10 person.put("1001", "AAAA"); 11 person.put("1002", "BBBB"); 12 person.put("1003", "CCCC"); 13 person.put("1004", "DDDD"); 14 person.put("1005", "EEEE"); 15 16 /*** 17 * ①通过Map.Entry来遍历(最喜欢) 18 */ 19 for (Map.Entry<String, String> entry : person.entrySet()) { 20 System.out.println("Key:" + entry.getKey() + "==>" + "Value:" + entry.getValue()); 21 } 22 System.out.println("+++++++++++++++++++++"); 23 /*** 24 * ②通过遍历Key集合来遍历Map(很多都是基于这个思路的变形,我归结于一大类) 25 */ 26 Iterator<String> it = person.keySet().iterator(); 27 while (it.hasNext()) { 28 Object obj = it.next(); 29 System.out.println(obj + ":" + person.get(obj)); 30 } 31 System.out.println("+++++++++++++++++++++"); 32 for (String key : person.keySet()) { 33 System.out.println(key + ":" + person.get(key)); 34 } 35 System.out.println("+++++++++++++++++++++"); 36 /*** 37 * ③直接遍历value的集合(但是不能同时的遍历key) 38 */ 39 for (String value : person.values()) { 40 System.out.println(value); 41 } 42 } 43 }
来源:https://www.cnblogs.com/simpleJokerKing/p/7519143.html