本片主要介绍集合体系,以及各种集合容器的特点。
下面的代码演示遍历map集合的三种方式
package com.DoMap;
import java.util.*;
import java.util.Map.Entry;
public class IterateMap {
/**
* 遍历Map集合的三种方式
*/
public static void main(String[] args) {
Map<String, Student> map=new HashMap<String, Student>();
map.put("s1", new Student(21));
map.put("s2", new Student(22));
map.put("s3", new Student(23));
IterateMothod1(map);
IterateMothod2(map);
IterateMothod3(map);
}
/**
* 通过值的集合遍历Map
* @param map
*/
public static void IterateMothod1(Map<String, Student> map) {
Collection<Student> cls=map.values();
for(Student s:cls){
System.out.println(s.getAge());
}
}
/**
* 通过键的集合遍历Map
* @param map
*/
public static void IterateMothod2(Map<String, Student> map) {
Set<String> ks=map.keySet();
Iterator<String> it=ks.iterator();
while(it.hasNext()){
//获取键
String key=it.next();
//通过键获取值
Student stu=map.get(key);
System.out.println(stu.getAge());
}
}
/**
* 通过entry(键值对)集合遍历Map
* @param map
*/
public static void IterateMothod3(Map<String, Student> map) {
Set<Entry<String, Student>> es=map.entrySet();
for(Entry<String, Student> entry:es){
System.out.println(entry.getKey());//获取键的值
System.out.println(entry.getValue().getAge());
}
}
}