HashMap
คล้ายๆกับ Dictionary
คือใส่ค่านึงไปเพื่อคนหาอีกค่านึง
ตัวอย่างนี้ใส่ตัวเลข เพื่อหาข้อความของตัวเลขนั้น
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
package jackapplication; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class JackApplication { public static void main(String[] args) { /* This is how to declare HashMap */ HashMap<Integer, String> hmap = new HashMap<Integer, String>(); /*Adding elements to HashMap*/ hmap.put(12, "Chaitanya"); hmap.put(2, "Rahul"); hmap.put(7, "Singh"); hmap.put(49, "Ajeet"); hmap.put(3, "Anuj"); /* Display content using Iterator*/ System.out.println("Display content using Iterator"); Set set = hmap.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry mentry = (Map.Entry) iterator.next(); System.out.print("key is: " + mentry.getKey() + ", and Value is: "); System.out.println(mentry.getValue()); } System.out.println(); /* Get values based on key*/ System.out.println("Get values based on key"); String var = hmap.get(2); System.out.println("Value at index 2 is: " + var); System.out.println(); /* Remove values based on key*/ System.out.println("Remove values based on key"); hmap.remove(3); System.out.println("Map key and values after removal:"); Set set2 = hmap.entrySet(); Iterator iterator2 = set2.iterator(); while (iterator2.hasNext()) { Map.Entry mentry2 = (Map.Entry) iterator2.next(); System.out.print("Key is: " + mentry2.getKey() + ", and Value is: "); System.out.println(mentry2.getValue()); } System.out.println(); } } |
ตัวอย่างผลลัพธ์
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Display content using Iterator key is: 49, and Value is: Ajeet key is: 2, and Value is: Rahul key is: 3, and Value is: Anuj key is: 7, and Value is: Singh key is: 12, and Value is: Chaitanya Get values based on key Value at index 2 is: Rahul Remove values based on key Map key and values after removal: Key is: 49, and Value is: Ajeet Key is: 2, and Value is: Rahul Key is: 7, and Value is: Singh Key is: 12, and Value is: Chaitanya |
Link