黑马程序员技术交流社区

标题: Map集合的四种遍历方式 [打印本页]

作者: F305176    时间: 2016-4-6 22:14
标题: Map集合的四种遍历方式
基本类是学生类(属性 name,age)用Student对象作为Key,住址为值,创建Map集合使用HashMap,遍历方式:1,增强for循环(EntrySet)    2.增强for循环(keySet)    3.使用迭代器遍历(EntrySet)     4.使用迭代器遍历(keySet)
  1. class Test01 {
  2.         public static void main(String[] args) {
  3.                 // 1.定义HashMap集合,键为Student对象,值为String类型的对象,表示地址
  4.                 HashMap<Student, String> map = new HashMap<>();
  5.                 map.put(new Student("张三", 20), "北京");
  6.                 map.put(new Student("李四", 20), "南京");
  7.                 map.put(new Student("王五", 20), "上海");


  8.                 // 遍历方式一:增强for循环(entrySet)
  9.                 for (Map.Entry<Student, String> entry : map.entrySet()) {
  10.                         System.out.println(entry.getKey() + "=" + entry.getValue());
  11.                 }
  12.                
  13.                 //遍历方式二:增强for循环(keySet)
  14.                 for(Student student :map.keySet()) {
  15.                         String address = map.get(student);
  16.                         System.out.println(student+"="+address);
  17.                 }
  18.                
  19.                 // 遍历方式三:迭代器(通过entrySet())
  20.                 Set<Map.Entry<Student, String>> set = map.entrySet();
  21.                 Iterator<Map.Entry<Student, String>> it = set.iterator();
  22.                 while (it.hasNext()) {
  23.                         Map.Entry<Student, String> entry = it.next();
  24.                         System.out.println(entry.getKey() + "=" + entry.getValue());
  25.                 }

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

  34.         }
  35. }
复制代码







作者: 善良的死神达乐    时间: 2016-5-19 21:34
咳~~~~~~~天天这黑马币啊!!!!!!!!!!!!!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2