java 中 Map遍历

来源:互联网 发布:c语言猴子吃桃递归 编辑:程序博客网 时间:2024/04/29 05:24

第二种方法效率更高

法①
Map map = new HashMap();
    Iterator it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        Object key = entry.getKey();
        Object value = entry.getValue();
}

 例子:

package com.cric.cat;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MapTest1 {

 public static void main(String[] args) {
  Student stu1=new Student("告诫去", "农大");
  Student stu2 = new Student("往基隆", "海大");
  Map M = new HashMap();
  M.put("jay",stu1);
  M.put("wang", stu2);
  
  Iterator it=M.entrySet().iterator();
  while(it.hasNext()){
   Map.Entry entry=(Map.Entry)it.next();
   Object key=entry.getKey();
   Object value=entry.getValue();
   System.out.println(key);
   System.out.println(value);
  }
  
 }

}

package com.cric.cat;

public class Student {
 private String name;
 private String school;

 public Student(String name, String school) {
  this.name = name;
  this.school = school;

 }

 public String toString() {
  return school + "毕业的" + name;
 }
}


法②
 HashMap<String, String> map = new HashMap<String, String>();

  map.put("jay", stu1.toString());
  map.put("wang", stu2.toString());

  for (Entry b : map.entrySet()) {
   System.out.println(b.getKey());
   System.out.println(b.getValue());

例子:

package com.cric.cat;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class MapTest {

 public static void main(String[] args) {
  Student stu1 = new Student("告诫去", "农大");
  Student stu2 = new Student("往基隆", "海大");
  HashMap<String, String> map = new HashMap<String, String>();

  map.put("jay", stu1.toString());
  map.put("wang", stu2.toString());

  for (Entry b : map.entrySet()) {
   System.out.println(b.getKey());
   System.out.println(b.getValue());
  
  }

 }
}

package com.cric.cat;

public class Student {
 private String name;
 private String school;

 public Student(String name, String school) {
  this.name = name;
  this.school = school;

 }

 public String toString() {
  return school + "毕业的" + name;
 }
}

原创粉丝点击