遍历Map集合的两种方式
方法一:通过键找值的方式
import java.util.*;
public class Practice {
public static void main(String[] args) {
Map<String,Integer> h = new HashMap<>(); //这里使用了多态
h.put("张三",21);
h.put("李四",23);
h.put("王五",25);
Set<String> s = h.keySet(); //使用Map集合中的方法keySet(),把Map集合的所有的键取出来,存储到一个set集合s当中
Iterator<String> it = s.iterator(); //生成一个迭代器
while(it2.hasNext()){
System.out.println(h.get(it2.next()));
}
}
方法二:Map集合遍历键值对的方式
import java.util.*;
public class Practice {
public static void main(String[] args) {
Map<String,Integer> h = new HashMap<>();
h.put("张三",21);
h.put("李四",23);
h.put("王五",25);
Set<Map.Entry<String, Integer>> e = h.entrySet(); //这里使用的Map方法中的entrySet(), 返回此映射中包含的映射关系的 Set 视图。把Map集合中多个Entry对象取出来,并存储到一个集合中
Iterator<Map.Entry<String, Integer>> it = e.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
此处还可使用Entry对象中的方法**getKey()和getValue()**获取键与值,代码如下:
import java.util.*;
public class Practice {
public static void main(String[] args) {
Map<String,Integer> h = new HashMap<>();
h.put("张三",21);
h.put("李四",23);
h.put("王五",25);
Set<Map.Entry<String, Integer>> e = h.entrySet(); // 把Entry对象存储进一个Set集合e
Iterator<Map.Entry<String, Integer>> it = e.iterator();
while(it.hasNext()){
System.out.println(it.next().getKey()); //获取键
System.out.println(it.next().getValue()); //获取值
}
}