ตัวอย่าง
package demo.loop;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class LoopMap {
/**
* @param args
*/
public static void main(String[] args) {
Map<string string=""> map = new HashMap<string string="">();
map.put("1", "loop");
map.put("2", "map");
map.put("3", "in");
map.put("4", "java");
System.out.println("Example 1...");
// Map -> Set -> Iterator -> Map.Entry
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
System.out.println("The key is: " + mapEntry.getKey() + ",value is :" + mapEntry.getValue());
}
System.out.println("Example 2...");
for (Map.Entry<string string=""> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
System.out.println("Example 3...");
for (Object key : map.keySet()) {
System.out.println("Key : " + key.toString() + " Value : " + map.get(key));
}
}
}
ผลลัพธ์ที่ได้คือ
Example 1... The key is: 3,value is :in The key is: 2,value is :map The key is: 1,value is :loop The key is: 4,value is :java Example 2... Key : 3 Value : in Key : 2 Value : map Key : 1 Value : loop Key : 4 Value : java Example 3... Key : 3 Value : in Key : 2 Value : map Key : 1 Value : loop Key : 4 Value : java
0 comments:
Post a Comment