ปัญหา: Map มี value เป็น null ต้องการแทนที่ด้วย default
ตัวอย่างโค้ด (Stream API - Java 8+)
import java.util.*;
import java.util.stream.Collectors;
public class Demo {
public static Map replaceNulls(Map map, V defaultValue) {
if (map == null) return Collections.emptyMap();
return map.entrySet().stream()
.map(entry -> {
if (entry.getValue() == null) {
// สร้าง entry ใหม่ (immutable) หรือแก้ในที่ (mutable)
return new AbstractMap.SimpleEntry<>(entry.getKey(), defaultValue);
}
return entry;
})
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> v1, // merge function (ไม่ควรเกิด duplicate key)
LinkedHashMap::new // รักษาลำดับ
));
}
// In-place mutation version (simpler)
public static void replaceNullsInPlace(Map map, V defaultValue) {
if (map == null) return;
map.replaceAll((k, v) -> v == null ? defaultValue : v);
}
public static void main(String[] args) {
Map map = new LinkedHashMap<>();
map.put(1, null);
map.put(2, 56);
map.put(3, null);
map.put(4, 99);
System.out.println("Original: " + map);
// Version 1: New map (immutable approach)
Map newMap = replaceNulls(map, 0);
System.out.println("New map: " + newMap);
System.out.println("Original unchanged: " + map);
// Version 2: In-place (mutable)
replaceNullsInPlace(map, 0);
System.out.println("In-place: " + map);
}
}
ผลลัพธ์
Original: {1=null, 2=56, 3=null, 4=99}
New map: {1=0, 2=56, 3=0, 4=99}
Original unchanged: {1=null, 2=56, 3=null, 4=99}
In-place: {1=0, 2=56, 3=0, 4=99}
วิธีอื่นๆ
| วิธี | Code | Mutable? |
| replaceAll (Java 8) | map.replaceAll((k,v) -> v==null ? def : v) | Yes |
| forEach + put | map.forEach((k,v) -> { if(v==null) map.put(k, def); }) | Yes |
| Stream + collect | map.entrySet().stream()...collect(toMap(...)) | No (new map) |
| ComputeIfAbsent | ไม่ใช้ได้ (key มีอยู่แล้ว value=null) | - |
ข้อควรระวัง
Map.replaceAll() mutate original map - thread safety?
- ConcurrentHashMap: ใช้
computeIfPresent หรือ replace แบบ atomic
- Null values vs Absent keys:
get(key) == null อาจหมายถึง key ไม่มี หรือ value เป็น null → ใช้ containsKey() แยก