通過java增強for循環for each遍歷Map中的數據



首先取得Map中的數據方法如下圖所示,在java普通的for循環當中,一般是按照如下圖1,圖2的方法,現將Map的keyset或者entrySet保存在一個set集合當中,然後對set集合使用iterator迭代器,進行迭代循環。但是今天要介紹的是使用增強for循環for each進行對Map中數據元素進行迭代。


第一種:

@Test
	public void test() {
		Map<Integer, String> map=new HashMap<Integer, String>();
		
		map.put(1, "this is 1");
		map.put(2, "this is 2");
		map.put(3, "this is 3");
		map.put(4, "this is 4");
		
		for (Object obj : map.keySet()) {
			String key= (String) obj;
			String value = map.get(key);
			System.out.println("key is "+key+"value is "+value);
		}
	}

第二種:


@Test
	public void test2() {
		Map<Integer, String> map=new HashMap<Integer, String>();
		map.put(1, "this is 1");
		map.put(2, "this is 2");
		map.put(3, "this is 3");
		map.put(4, "this is 4");
		
		for (Object obj : map.entrySet()) {
			//將取得的map的entryset保存
			Map.Entry entry= (Entry) obj;
			String key=entry.getKey().toString();
			String value=(String) entry.getValue();
			System.out.println("key is "+key+"value is:" +value);
			
		}
	}




主要思路就是keySet屬性,還有entrySet屬性繼承了迭代器的接口。所以只要實現了迭代器的接口的數據類型,都可以用增強for循環取除數據。雖然Map沒有實現迭代器接口。但是Map中的set集合取出之後就可以迭代了。進而何以使用增強for循環了。

下面是全部代碼。

package Demo;

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

import org.junit.Test;

public class demo {
	@Test
	public void test() {
		Map<Integer, String> map=new HashMap<Integer, String>();
		
		map.put(1, "this is 1");
		map.put(2, "this is 2");
		map.put(3, "this is 3");
		map.put(4, "this is 4");
		
		for (Object obj : map.keySet()) {
			String key= (String) obj;
			String value = map.get(key);
			System.out.println("key is "+key+"value is "+value);
		}
	}

	@Test
	public void test2() {
		Map<Integer, String> map=new HashMap<Integer, String>();
		map.put(1, "this is 1");
		map.put(2, "this is 2");
		map.put(3, "this is 3");
		map.put(4, "this is 4");
		
		for (Object obj : map.entrySet()) {
			//將取得的map的entryset保存
			Map.Entry entry= (Entry) obj;
			String key=entry.getKey().toString();
			String value=(String) entry.getValue();
			System.out.println("key is "+key+"value is:" +value);
			
		}
	}
	
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章