Map三种遍历方式packagedecorator;importjava.util.Collection;importjava.util.HashMap;importjava.util.Map;importjava.util.Map.Entry;importjava.util.Set;importorg.junit.Before;importorg.junit.Test;/** * 对于Map的三种方式遍历 1.keySet() 2.values() 3.entrySet()
* 三种方式得到Set之后,都可以使用 foreach或者iterator, 不能使用for,因为数据结构决定的 *
* @author Administrator *
*/ publicclassMapCycle {
Map<Integer, String>map;//准备好数据@BeforepublicvoidtestData() {
map=newHashMap<>();
map.put(1, "凌一");
map.put(2, "凌二");
map.put(3, "凌三");
map.put(4, "凌四");
map.put(5, "凌五");
}/**测试三种方式,这三种方式最后都是遍历Set,于是都可以使用
foreach或者Iterator **///方式1: keySet()方法获取到Set(key)@TestpublicvoidtestFirst() {
Set<Integer> set =map.keySet();for(Integer integer : set) {
System. out.PRintln( map.get(integer));
}
}//方式2:values()方法获取到Collection(value)@TestpublicvoidtestSecond() {
Collection<String> collection =map.values();for(String string : collection) {
System. out.println(string);
}
}//方式3:entrySet()方法获取到Set<Entry<key,value>>@TestpublicvoidtestThird() {
Set<Entry<Integer, String>> entries =map.entrySet();for(Entry<Integer, String>entry : entries) {
System. out.println(entry.getValue());
}
}
}