// 單筆 Map
Map map2 = {name="Wang", od=234};
// List
找出 map1 中 od == map2.od 的元素(即 {age=31, od=234})並提取。
Integer targetOd = (Integer) map2.get("od");
Map result = map1.stream()
.filter(m -> targetOd.equals(m.get("od")))
.findFirst()
.orElse(null);
if (result != null) {
// 找到符合項
System.out.println(result); // {age=31, od=234}
}
Map found = null;
for (Map m : map1) {
if (targetOd.equals(m.get("od"))) {
found = m;
break;
}
}
// 將 map1 轉為 Map,O(1) 查找
Map> index = new HashMap<>();
for (Map m : map1) {
index.put((Integer) m.get("od"), m);
}
Map result = index.get(targetOd);
equals 而非 == 比較包裝型別(Integer)。od 鍵存在且非 null,避免 NullPointerException。od,Stream findFirst 只取第一筆;需全部請用 collect(Collectors.toList())。針對 List 依特定鍵值比對,Java 8 Stream API 寫法簡潔且可讀;資料量大時建立 HashMap 索引可大幅提升查詢效能。