首先取得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);
}
}
}