基本上是如下3种或者4中方法
public class MapTest {
private Map<String, String> map = null;
@Before
public void before() {
map = new HashMap<String, String>();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
map.put("4", "d");
}
/**
* 利用Map的内部接口Entry来实现 Entry(key-value)相当于Map中的一条记录 foreach
*/
@Test
public void method1() {
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("the key is:" + entry.getKey()
+ " the value is :" + entry.getValue());
}
}
/**
* 如果只是需要获取里面的key,value,用这种方法就可以了
* 当然也可以获取key及get方法获取相应的value,即第4种方法
*/
@Test
public void method2() {
for (String key : map.keySet()) { // 因为key是不重复的,所以keySet返回值是一个set
System.out.println("the key is: " + key);
}
for (String value : map.values()) { //因为value是可以重复的,所以values返回值是一个Collection
System.out.println("the value is: " + value);
}
}
/**
* 使用itreator迭代
*/
@Test
public void method3() {
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
System.out.println("the key is:" + entry.getKey()
+ " the value is :" + entry.getValue());
}
}
}
运行结果
the key is:3 the value is :c
the key is:2 the value is :b
the key is:1 the value is :a
the key is:4 the value is :d
为什么是这个顺序还不太清楚