集合中的三种遍历方式,如下代码:
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TestMap {
public static void main(String[] args) {
Map map = new HashMap();
Student s1 = new Student("宋江", "1001", 38);
Student s2 = new Student("卢俊义", "1002", 35);
Student s3 = new Student("吴用", "1003", 34);
map.put("1001", s1);
map.put("1002", s2);
map.put("1003", s3);
Map subMap = new HashMap();
subMap.put("1008", new Student("tom", "1008", 12));
subMap.put("1009", new Student("jerry", "1009", 10));
map.putAll(subMap);
work(map);
workByKeySet(map);
workByEntry(map);
}
//第一种方式
public static void work(Map map) {
Collection c = map.values();
Iterator it = c.iterator();
for (; it.hasNext();) {
System.out.println(it.next());
}
}
//第二种方式
public static void workByKeySet(Map map) {
Set key = map.keySet();
for (Iterator it = key.iterator(); it.hasNext();) {
String s = (String) it.next();
System.out.println(map.get(s));
}
}
//第三种方式
public static void workByEntry(Map map) {
Set> set = map.entrySet();
for (Iterator> it = set.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
System.out.println(entry.getKey() + "--->" + entry.getValue());
}
}
}
class Student {
private String name;
private String id;
private int age;
public Student(String name, String id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
@Override
public String toString() {
return "Student{" + "name=" + name + "id=" + id + "age=" + age + '}';
}