package com.JUnit;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("unchecked")
public class TestMap {
public static void main(String[] args) {
Map<String, Student> map = new HashMap<String, Student>();
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<String, Student> subMap = new HashMap<String, Student>();
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);
workByKeySetEntry(map);
}
/** 直接取values **/
public static void work(Map<String, Student> map) {
Collection<Student> c = map.values();
Iterator it = c.iterator();
for (; it.hasNext();) {
Student student = (Student) it.next();
System.out.println(student);
System.out.println(student.getName());
}
}
/** 利用keyset进行遍历 **/
public static void workByKeySet(Map<String, Student> map) {
Set<String> key = map.keySet();
for (Iterator it = key.iterator(); it.hasNext();) {
String s = (String) it.next();
System.out.println(map.get(s));
}
}
/** 灵活取值 **/
public static void workByKeySetEntry(Map<String, Student> map) {
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
Student val = (Student) entry.getValue();
System.out.println("key:" + key + ",value:" + val + ",name:" + val.getName());
}
}
/** 灵活取对象的值 **/
public static void workByEntry(Map<String, Student> map) {
Set<Map.Entry<String, Student>> set = map.entrySet();
for (Iterator<Map.Entry<String, Student>> it = set.iterator(); it
.hasNext();) {
Map.Entry<String, Student> entry = (Map.Entry<String, Student>) it
.next();
System.out.println(entry.getKey() + "--->" + entry.getValue());
System.out.println(entry.getValue().getAge());
}
}
}
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 + '}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
本文于 2012年11月12日 写于CSDN
https://blog.csdn.net/RSun1/article/details/8176716