1.获取所有的key用Set来接,根据key依次来用get()方法来获取value
public static void func1 (Map map) {
Set<Integer> keySet = map.keySet();
for (Integer key: keySet) {
System.out.println("key = "+ key + ", value = " + map.get(key) + ", ");
}
}
2.使用Map.Entry对象遍历
public static void func2 (Map map) {
Set<Map.Entry<Integer, String>> entries = map.entrySet();
for (Map.Entry<Integer, String> entry: entries) {
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
}
}
3.使用迭代器(Map接口没有继承Iterable和Collection接口)
public static void func3 (Map map) {
// 获取到迭代器
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
}
}
4.用Map.values()方法来获取值用Collection类型来接(因为值可以重复)
public static void func4 (Map map) {
Collection<String> values = map.values();
for (String value: values) {
System.out.println(value);
}
}