常用容器Map的四种遍历方式

常用的容器包括:List、Set和Map,三种容器里Map的遍历稍微复杂,记录一下。

Map遍历的方式有四种:

		public static void main(String[] args) {      
		  	Map map = new HashMap();    
		  	map.put("key1", "val1");    
		  	map.put("key2", "val2");    
		  	map.put("key3", "val3"); 

		  	//通过Map.entrySet遍历
			for (Map.Entry entry : map.entrySet()) {    
		   		System.out.println("key= " + entry.getKey() + " and val= " + entry.getValue());    
		  	} 
			  
			//通过Map.keySet遍历
			for (String key : map.keySet()) {    
		   		System.out.println("key= "+ key + " and val= " + map.get(key));    
		 	 }
		  
		  	//通过Map.entrySet使用iterator遍历
		  	Iterator> it = map.entrySet().iterator();    
		  		while (it.hasNext()) {    
		   			Map.Entry entry = it.next();    
		   			System.out.println("key= " + entry.getKey() + " and val= " + entry.getValue());    
		  		}  
			}
		  
		  	//通过Map.values()遍历
		  	for (String v : map.values()) {    
		   		System.out.println("val= " + v);    
		  	}    
		 } 




你可能感兴趣的:(Java复习-容器类,常见数据结构与算法)