Mapの遍歴方式まとめ
1661 ワード
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MapTest {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "1");
map.put("2", "2");
map.put("3", "3");
// : Map.keySet key value
System.out.println(" Map.keySet key value:");
for (String key : map.keySet()) {
System.out.println("key= " + key + " and value= " + map.get(key));
}
// : Map.entrySet iterator key value
System.out.println(" Map.entrySet iterator key value:");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= "
+ entry.getValue());
}
// : Map.entrySet key value
System.out.println(" Map.entrySet key value:");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= "
+ entry.getValue());
}
// : Map.values() value, key
System.out.println(" Map.values() value:");
for (String v : map.values()) {
System.out.println("value= " + v);
}
}
}