Map三種遍歷方式,map三種
package decorator;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
/**
* 對於Map的三種方式遍歷 1.keySet() 2.values() 3.entrySet()
* 三種方式得到Set之後,都可以使用 foreach或者iterator, 不能使用for,因為數據結構決定的 *
* @author Administrator *
*/
public class MapCycle {
Map<Integer, String> map;
// 准備好數據
@Before
public void testData() {
map = new HashMap<>();
map.put(1, "凌一");
map.put(2, "凌二");
map.put(3, "凌三");
map.put(4, "凌四");
map.put(5, "凌五");
}
/** 測試三種方式,這三種方式最後都是遍歷Set,於是都可以使用
foreach或者Iterator **/
// 方式1: keySet()方法獲取到Set(key)
@Test
public void testFirst() {
Set<Integer> set = map.keySet();
for (Integer integer : set) {
System. out.println( map.get(integer));
}
}
// 方式2:values()方法獲取到Collection(value)
@Test
public void testSecond() {
Collection<String> collection = map.values();
for (String string : collection) {
System. out.println(string);
}
}
// 方式3:entrySet()方法獲取到Set<Entry<key,value>>
@Test
public void testThird() {
Set<Entry<Integer, String>> entries = map.entrySet();
for (Entry<Integer, String> entry : entries) {
System. out.println(entry.getValue());
}
}
}