Map集合遍历
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Traversal {
public static void mapTraversal1(Map<String,Integer> map){
System.out.println("第一种:通过Map.keySet遍历key和value");
//Set<K> keySet() 返回集合中包含的键的Set视图。
for (String s : map.keySet()) {
Integer n = map.get(s);//得到每个 key 对应用的值 value
System.out.println(s + " : " + n);
}
}
public static void mapTraversal2(Map<String,Integer> map){
System.out.println("第二种:通过Map.entrySet使用iterator遍历key和value");
//Set<Map.Entry<K,V>> entrySet() 返回集合中包含的映射的Set视图
//Iterator<E> iterator() 返回此集合中的元素的迭代器。
//Iterator<E> 没有关于元素返回顺序的保证(除非这个集合是提供保证的某个类的实例)
Iterator<Map.Entry<String,Integer>> iterator = map.entrySet().iterator();
//boolean hasNext() 如果迭代具有更多的元素,则返回 true
//即如果 next() 返回一个元素而不是抛出一个异常,则返回 true
while (iterator.hasNext()) {
Map.Entry<String,Integer> entry = iterator.next();//E next()返回迭代中的下一个元素
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
public static void mapTraversal3(Map<String,Integer> map){
System.out.println("第三种:通过Map.entrySet遍历key和value");
//Set<Map.Entry<K,V>> entrySet() 返回集合中包含的映射的Set视图
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
public static void mapTraversal4(Map<String,Integer> map) {
System.out.println("第四种:通过Map.values()遍历所有的value,但不能遍历key");
//Collection<V> values() 返回此集合中包含的值的Collection视图
for (Integer v : map.values()) {
System.out.println("value= " + v);
}
}
}
程序测试
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<>();
map.put("dbca",1);
map.put("abcd",2);
map.put("efgh",3);
map.put("dbca",4);
map.put("abcd",2);
map.put("hhhh",3);
mapTraversal1(map);
mapTraversal2(map);
mapTraversal3(map);
mapTraversal4(map);
}
测试结果: