Map集合的三種遍歷方法
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapTest {
public static void main(String[] args) {
Map map = new HashMap();
Student s1 = new Student(1,"zhangsan",88);
Student s2 = new Student(2,"lisi",87);
Student s3 = new Student(3,"wangwu",99);
Student s4 = new Student(4,"zhaoliu",77);
map.put(s1, 1);
map.put(s2, 1);
map.put(s3, 1);
map.put(s4, 1);
System.out.println("map中元素個數是:"+map.size());
System.out.println("key為10的value值:"+map.get(10));
System.out.println(map.containsKey(true));
map.remove("hello");
map.remove(true,false);
System.out.println("map中元素個數:"+map.size());
//遍歷map(1)
Set set = map.keySet();
Iterator site = set.iterator();
while (site.hasNext()) {
Object key = site.next();
Object value = map.get(key);
System.out.println(key+" = "+value);
}
System.out.println("----------------------------");
//遍歷map(2)
Set kvs =map.entrySet();
Iterator kvite = kvs.iterator();
while (kvite.hasNext()) {
Map.Entry kv = (Map.Entry) kvite.next();
Object key = kv.getKey();
Object value = kv.getValue();
System.out.println(key+" = "+value);
}
System.out.println("--------------------------");
//遍歷map(3)
Collection values = map.values();
for(Object value:values){
System.out.println("value:"+value);
}
}
}