您的位置:首页 > 编程语言 > Java开发

【Java】Map集合的几种遍历方式

2016-09-04 00:23 591 查看
【前言】

在这里与大家分享一下Map集合的几种遍历方式,虽然工作过一年多的时间了,但是我还是觉集合遍历是很常用的,而且Map集合遍历容易混淆遗忘。这里与大家一起温习一下。

public class Test1 {
public static void main(String[] args) {
// 1.定义HashMap集合,键为Student对象,值为String类型的对象,表示地址
HashMap<Student, String> map = new HashMap<>();
map.put(new Student("张三", 20, 15), "北京");
map.put(new Student("李四", 20,20), "南京");
map.put(new Student("王五", 20,45), "上海");
map.put(new Student("赵六", 20,56), "广州");
map.put(new Student("孙七", 20,78), "深圳");
//遍历方式一:增强for循环(entry)
for(Map.Entry<Student, String> entry :map.entrySet()){
System.out.println(entry.getKey()+""+entry.getValue());
}
//遍历方式二:增强for循环(keySet)
System.out.println("--------------------------------------------");
for(Student student : map.keySet()){
String address = map.get(student);
System.out.println(student+"::"+address);

}
//遍历集合方式三、迭代器
System.out.println("---------------------------------");
Set<Map.Entry<Student,String>> set = map.entrySet();
Iterator<Map.Entry<Student, String>> it = set.iterator();
while(it.hasNext()){
Map.Entry<Student,String> entry = it.next();
System.out.println(entry.getKey() + "::" + entry.getValue());

}
// 遍历方式四:迭代器(通过keySet())
System.out.println("-----------------------------------------");
Set<Student> keySet = map.keySet();
Iterator<Student> it2 =keySet.iterator();
while(it2.hasNext()){
Student student = it2.next();
String address = map.get(student);
System.out.println(student +"::"+address);
}
}


执行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: