1、Map获取值的集合:values()方法
2、Map获取键的集合:keySet()方法
3、Map获取键值对的集合:entrySet()方法
方法一和方法二的遍历要使用Irerator迭代器,方法三的遍历使用Map.Entry接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。
例子程序:TestMap.java
package com.test.traversalMap;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class TestMap {
public static void main(String args[]) {
Map<String, String> m = new HashMap<String, String>();
m.put("99", "sun");
m.put("100", "mon");
m.put("101", "tues");
m.put("102", "wed");
m.put("103", "thur");
m.put("104", "fri");
m.put("105", "sat");
/*
* 1、遍历值
*/
System.out.println("========方法一========");
Collection<String> c = m.values();
Iterator<String> iter = c.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
System.out.println("======================");
/*
* 2、遍历键
*/
System.out.println("========方法二========");
Set<String> s = m.keySet();
Iterator<String> iter2 = s.iterator();
while (iter2.hasNext()) {
System.out.println(iter2.next());
}
System.out.println("======================");
/*
* 3、遍历键值对
*/
System.out.println("========方法三========");
Set<Map.Entry<String, String>> entry = m.entrySet();
for (Map.Entry<String, String> ss : entry) {
System.out.println("key:" + ss.getKey() + " value:" + ss.getValue());
}
System.out.println("======================");
}
}
运行结果:
========方法一========
sat
fri
thur
wed
sun
tues
mon
======================
========方法二========
105
104
103
102
99
101
100
======================
========方法三========
key:105 value:sat
key:104 value:fri
key:103 value:thur
key:102 value:wed
key:99 value:sun
key:101 value:tues
key:100 value:mon
======================