天天看點

map周遊的四種方法

public class Demo01 {
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("01", "this is 01");
		
		//第一種周遊方式 擷取key-value 放入entry中 進而擷取鍵值 
		Set<Entry<String,String>> set = map.entrySet();
		for(Entry<String,String> entry : set) {
			System.out.println("key is : "+entry.getKey()+",value is "+entry.getValue());
		}
		
		System.out.println("------------------------------------------------------");
		
		//第二種周遊方式 隻擷取key 再從map中擷取value
		for(String key :map.keySet()) {
			System.out.println("key is : "+key+",value is "+map.get(key));
		}
		
		System.out.println("------------------------------------------------------");
		
		//第三種周遊方式 隻擷取value
		for(String value : map.values()) {
			System.out.println("value is "+value);
		}
		System.out.println("------------------------------------------------------");
		
		//第四中周遊方式 疊代器周遊
		Iterator<Entry<String, String>> it = map.entrySet().iterator();
		while(it.hasNext()) {
			Entry<String, String> next = it.next();
			//這樣的寫法不合理 應為這樣寫會調用多次next 是以導緻越界 然後報錯java.util.NoSuchElementException
			//System.out.println("key is : "+it.next().getKey()+",value is "+it.next().getValue());
			System.out.println("key is : "+next.getKey()+",value is "+next.getValue());
		}
	}
}