1. 程式人生 > >Java Map的幾種迴圈方式學習總結

Java Map的幾種迴圈方式學習總結

1:根據JDK的新特性,用For迴圈Map,例如迴圈Map的Key

Map<Object , Object> map = new HashMap<Object, Object>();
		for (int i = 0; i < 10; i++) {
			map.put(i, i+1);
		}
		for (Object key : map.keySet()) {
			System.out.println("key = " + key);
		}


2:對整Map的key和value都進行迴圈,如下:
for(Map.Entry<String, Object> entry : paraMap.entrySet())    
{    
    System.out.println(entry.getKey()+": "+entry.getValue());    
} 

3:使用Iterator 
Iterator it = paraMap.entrySet().iterator();    
while (it.hasNext())     
{    
        Map.Entry map = (Map.Entry)it.next();    
        System.out.println(map .getKey() + " = " + map .getValue());    
 }  

對上面的內容進行更新!將三種方式完整呈現!

package com.dufyun.javase.jihe;

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

/**
 * 練習迴圈map集合中key和value的方法
 * @author aflyun
 * 
 *
 */
public class TestMap {
	
	   
	public static void main(String[] args) {
		Map<Object , Object> map = new HashMap<Object, Object>();
		for (int i = 0; i < 10; i++) {
			map.put(i, i+1);
		}
		
		firstLoopMap(map);
		secodnLoopMap(map);
		thirdLoopMap(map);
	}
	
	/**
	 * 1:迴圈 map 中的key<br/>
	 * 	 根據JDK的新特性,用For迴圈Map,例如迴圈Map的Key 和 value 
	 * @param map
	 */
	public static void firstLoopMap(Map<Object, Object> map) {
		for (Object key : map.keySet()) {
			System.out.println("key = " + key +"--value = " + map.get(key));
		}
	}
	/**
	 * 2:迴圈 map 中的key 和 value<br/>
	 * entrySet 
	 * @param map
	 */
	public static void secodnLoopMap(Map<Object , Object> map) {
		for (Map.Entry<Object, Object> entry : map.entrySet()) {
			System.out.println("key = " + entry.getKey() +"--value = " + entry.getValue());
		}
	}
	
	/**
	 * 3:迴圈Map的key 和value<br/>
	 * iterator
	 * @param map
	 */
	public static void thirdLoopMap(Map<Object, Object> map) {
		Iterator it = map.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry<Object, Object> m = (Entry<Object, Object>) it.next();
			System.out.println("key = " + m.getKey() +"---value = "+ m.getValue());
		}
				
	}
}

輸出的內容:
key = 0---value = 1
key = 1---value = 2
key = 2---value = 3
key = 3---value = 4
key = 4---value = 5
key = 5---value = 6
key = 6---value = 7
key = 7---value = 8
key = 8---value = 9
key = 9---value = 10