Iteration over HashMap ใน Java
HashMap<K, V> เก็บคู่ Key-Value การ Iterate สามารถทำได้หลายวิธี ขึ้นกับว่าต้องการ Key, Value, หรือทั้งคู่
ตัวอย่างที่ 1: ใน main โดยตรง
import java.util.HashMap;
import java.util.Map.Entry;
public class Demo {
public static void main(String[] args) {
System.out.println("The required packages have been imported");
HashMap inputMap = new HashMap<>();
inputMap.put("Java", "Enterprise");
inputMap.put("Python", "ML/AI");
inputMap.put("JavaScript", "Frontend");
inputMap.put("Mysql", "Backend");
System.out.println("The HashMap is defined as: " + inputMap);
// 1. Iterate Keys เท่านั้น
System.out.print("\nThe keys of the Hashmap are: ");
for (String key : inputMap.keySet()) {
System.out.print(key + ", ");
}
// 2. Iterate Values เท่านั้น
System.out.print("\nThe Values of the Hashmap are: ");
for (String value : inputMap.values()) {
System.out.print(value + ", ");
}
}
}
ผลลัพธ์
The required packages have been imported
The HashMap is defined as: {Java=Enterprise, JavaScript=Frontend, Mysql=Backend, Python=ML/AI}
The keys of the Hashmap are: Java, JavaScript, Mysql, Python,
The Values of the Hashmap are: Enterprise, Frontend, Backend, ML/AI,
ตัวอย่างที่ 2: แยกเป็นเมธอด (OOP)
import java.util.HashMap;
class Demo {
static void printKeys(HashMap inputMap) {
System.out.print("\nThe keys of the Hashmap are: ");
for (String key : inputMap.keySet()) {
System.out.print(key + ", ");
}
}
static void printValues(HashMap inputMap) {
System.out.print("\nThe Values of the Hashmap are: ");
for (String value : inputMap.values()) {
System.out.print(value + ", ");
}
}
public static void main(String[] args) {
System.out.println("The required packages have been imported");
HashMap inputMap = new HashMap<>();
inputMap.put("Java", "Enterprise");
inputMap.put("Python", "ML/AI");
inputMap.put("JavaScript", "Frontend");
inputMap.put("Mysql", "Backend");
System.out.println("The HashMap is defined as: " + inputMap);
printKeys(inputMap);
printValues(inputMap);
}
}
วิธี Iterate แบบครบถ้วน (Key + Value พร้อมกัน)
1. entrySet() + for-each (แนะนำมากที่สุด)
for (Map.Entry entry : inputMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
2. Java 8+ forEach + Lambda
inputMap.forEach((key, value) ->
System.out.println("Key: " + key + ", Value: " + value)
);
3. Iterator บน entrySet()
Iterator> it = inputMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
// สามารถ remove ได้ปลอดภัย
// it.remove();
}
4. keySet() + get() (ไม่แนะนำ - ช้ากว่า)
for (String key : inputMap.keySet()) {
String value = inputMap.get(key); // Top-up lookup O(1) แต่ทำซ้ำ
System.out.println(key + " = " + value);
}
เปรียบเทียบประสิทธิภาพ
| วิธีการ |
Time |
เหมาะสำหรับ |
entrySet() for-each |
O(n) |
⭐ Best - เข้าถึง Key+Value พร้อมกัน ไม่ต้อง lookup ซ้ำ |
forEach((k,v) -> ...) |
O(n) |
Clean syntax, Functional style |
keySet() + get() |
O(n) |
ต้องการ Key เท่านั้น แล้วค่อย get Value บางครั้ง |
values() |
O(n) |
ต้องการ Value เท่านั้น |
การลบขณะ Iterate (Safe Removal)
// ❌ ผิด - ConcurrentModificationException
for (Map.Entry e : map.entrySet()) {
if (e.getValue().equals("Backend")) map.remove(e.getKey());
}
// ✅ ถูก - ใช้ Iterator
Iterator> it = map.entrySet().iterator();
while (it.hasNext()) {
if (it.next().getValue().equals("Backend")) {
it.remove();
}
}
// ✅ Java 8+ - removeIf (บน entrySet view)
map.entrySet().removeIf(e -> e.getValue().equals("Backend"));
การ Filter/Transform ด้วย Stream API (Java 8+)
// Filter และ Print
map.entrySet().stream()
.filter(e -> e.getValue().contains("End"))
.forEach(e -> System.out.println(e.getKey() + " -> " + e.getValue()));
// สร้าง Map ใหม่จากการ Transform
Map upperCaseMap = map.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().toUpperCase()
));
// หา Key ที่มี Value ตรงเงื่อนไข
List backendKeys = map.entrySet().stream()
.filter(e -> e.getValue().equals("Backend"))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
Map Implementations และ Iteration Order
| Map Type |
Iteration Order |
Null Key/Value |
| HashMap |
ไม่ระบุ (Random) |
✅ 1 null key, multiple null values |
| LinkedHashMap |
✅ Insertion Order / Access Order |
✅ |
| TreeMap |
✅ Sorted by Key |
❌ Null key (throws NPE) |
| Hashtable |
ไม่ระบุ |
❌ ไม่อนุญาต null |
| ConcurrentHashMap |
ไม่ระบุ |
❌ ไม่อนุญาต null |
สรุป
- entrySet() + for-each = วิธีมาตรฐานที่ดีที่สุด (Key + Value พร้อมกัน)
- forEach(lambda) = สะดวก สั้น Java 8+
- keySet() = เมื่อต้องการ Key เท่านั้น
- values() = เมื่อต้องการ Value เท่านั้น
- ใช้ Iterator หรือ removeIf() สำหรับลบขณะ Iterate
- เลือก Map Implementation ให้ตรงความต้องการ Order