Map集合的四种遍历方式,分享:
Map<Student, String> hm = new HashMap<Student, String>();
hm.put(new Student("张三",23), "北京");
hm.put(new Student("李四",23), "上海");
hm.put(new Student("王五",24), "广州");
hm.put(new Student("赵六",25), "深圳");
//第一种方式:获取所有键的集合,再使用迭代器
Set<Student> set = hm.keySet();
Iterator<Student> it1 = set.iterator();
while(it1.hasNext()){
Student key = it1.next();
String value = hm.get(key);
System.out.println(key + "::" + value);
}
System.out.println("-----------------------------------");
//第二种方式:用keySet()方法获取所有键的集合,再利用增强for
for(Student key : hm.keySet()){
System.out.println(key + "::" + hm.get(key));
}
System.out.println("-----------------------------------");
//第三种方式:获取键值对对象集合,再获取迭代器遍历,再getKey();getValue();
Set<Map.Entry<Student, String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student, String>> it2 = entrySet.iterator();
while(it2.hasNext()){
Map.Entry<Student, String> en = it2.next();
Student key = en.getKey();
String value = en.getValue();
System.out.println(key + "::" + value);
}
System.out.println("-----------------------------------");
//第四种方式:获取键值对对象集合,再用增强for遍历
即:把原Map双列集合的每一对键值对包装成一个类似Person的对象):Map.Entry(Entry是Map的静态内部类)
Set<Map.Entry<Student, String>> entrySet2 = hm.entrySet();
for (Map.Entry<Student, String> entry : entrySet2) {
System.out.println(entry.getKey() + "::" + entry.getValue());
} |
|