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

来源:互联网 发布:java web filter 编辑:程序博客网 时间:2024/05/16 06:17

【前言】

在这里与大家分享一下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);}}

执行结果:


1 0
原创粉丝点击