【Map遍歴の4つの方法が超詳細】

2934 ワード

前言:map遍歴はmapに分けられる.keyset()とmap.entryset()は、反復器による直接的な遍歴と強化forサイクル遍歴の2つで、合計4つです.
ダイレクトコード
/**   
* Copyright: Copyright (c) 2018 Asiainfo-Linkage
* 
* @ClassName: MapDemo.java
* @Description:        
* @version: v1.0.0
* @author: chenx
* @date: 2018 10 16    10:34:53 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2018 10 16                  v1.0.0                   
*/
package com.cx.list;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**   
 * Copyright: Copyright (c) 2018 Asiainfo-Linkage
 * 
 * @ClassName: MapDemo.java
 * @Description:        
 * @version: v1.0.0
 * @author: chenx
 * @date: 2018 10 16    10:34:53 
 *
 * Modification History:
 * Date         Author          Version            Description
 *---------------------------------------------------------*
 * 2018 10 16                  v1.0.0                   
 */
public class MapDemo {
	public static void main(String[] args){
		Map map = new HashMap();
		map.put("a", 1);
		map.put("b", "22");
		map.put("c", "33");
		map.put("d", "555");
		each1(map);
		each2(map);
		each3(map);
		each4(map);
	}

	
	//         map.keySet()  
	public static  void each1(Map map){
		//1.  map     keyset,       set   
		Set set = map.keySet();
		//2.  set  ,   set       
		Iterator it = set.iterator();
		while(it.hasNext()){
			//  key 
			String key = it.next();
			Object value = map.get(key);
			System.out.println("Map   key: "+key+"====value: "+value);
		}
	}
	
	//     for     map.keySet()  
	public static void each2(Map map){
		for(String key:map.keySet()){
			Object value = map.get(key);
			System.out.println("Map   key: "+key+"====value: "+value);
		}
		
	}
	
	//         map.entrySet()  
	public static void each3(Map map){
		//1.  map    entrySet()              set  
		Set> entrySet = map.entrySet();
		//2.  set  
		Iterator> it = entrySet.iterator();
		while(it.hasNext()){
			//3.   set     ,       
			//it.next        , Map.Entry  
			Map.Entry entry = it.next();
			String key = entry.getKey();
			Object value = entry.getValue();
			System.out.println("Map   key: "+key+"====value: "+value);
			
		}
		
	}
	
	//     for     map.entrySet()  
	public static void each4(Map map){
		for(Map.Entry entry:map.entrySet()){
			String key = entry.getKey();
			Object value = entry.getValue();
			System.out.println("Map   key: "+key+"====value: "+value);
		}
	}
	
	
}