*********************************************************************************
*****************************Map两种遍历方式*******************************
*********************************************************************************
1 package ccms; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map; 6 import java.util.Set; 7 8 public class MapTest { 9 10 /** 11 * @param args 12 */ 13 public static void main(String[] args) { 14 Map<String,String> map = new HashMap<String,String>(); 15 map.put("1", "王者荣耀"); 16 map.put("2", "刺激战场"); 17 18 /*遍历1*/ 19 System.out.println("***********遍历1***********"); 20 Set<String> set = map.keySet(); 21 Iterator<String> it = set.iterator(); 22 while(it.hasNext()){ 23 String key = it.next(); 24 String value = map.get(key); 25 System.out.println("value-"+value); 26 } 27 28 /*遍历2*/ 29 System.out.println("***********遍历2***********"); 30 Set<Map.Entry<String, String>> s = map.entrySet(); 31 Iterator<Map.Entry<String, String>> i = s.iterator(); 32 while(i.hasNext()){ 33 Map.Entry<String, String> entry = i.next(); 34 String key = entry.getKey(); 35 String value = entry.getValue(); 36 System.out.println("key-"+key+"|value-"+value); 37 } 38 39 } 40 41 }
打印输出结果: ***********遍历1*********** value-刺激战场 value-王者荣耀 ***********遍历2*********** key-2|value-刺激战场 key-1|value-王者荣耀
原文地址:https://www.cnblogs.com/jiangaofeng/p/10827442.html
时间: 2024-10-13 04:04:56