如何迭代hashmap?
import java.util.Collection;
import java.util.hashmap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;/**
*
* @author Administrator
*/
public class StuMapTest { public static void main(String[] args) {
Map<String, Student> map = new HashMap<String, Student>();
Student s1 = new Student("001", "呂布", 30);
Student s2 = new Student("002", "趙云", 25);
Student s3 = new Student("003", "典韋", 33);
map.put("1", s1);
map.put("2", s2);
map.put("3", s3);
byValues(map);
keySet(map);
entrySet(map);
}
//entrySet方法遍歷
private static void entrySet(Map<String, Student> map){
Set<Map.Entry<String,Student>> set = map.entrySet();
for (Iterator<Map.Entry<String, Student>> i = set.iterator(); i.hasNext();) {
System.out.println(i.next().getValue()); }
}
//keySet方法遍歷
private static void keySet(Map<String, Student> map){
Set<String> set = map.keySet();
for (Iterator<String> i = set.iterator(); i.hasNext();) {
System.out.println(map.get(i.next()));
}
}//values方法遍歷
private static void byValues(Map<String, Student> map) {
Collection c = map.values();
for (Iterator<Student> i = c.iterator(); i.hasNext();) {
System.out.println(i.next()); }
}
}//定義一個student類
class Student {
private String id;
private String name;
private int age; public Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
} @Override
public String toString() {
return new StringBuilder().append(id).append(" ").append(name).append(" ").append(age).toString();
}
}