Map<String, String> map = new HashMap<>();
map.put("星期一", "Monday"); // 新增/修改
String v = map.get("星期六"); // 查詢
map.put("星期一", "Mon"); // 覆蓋
String removed = map.remove("星期六"); // 刪除並返回舊值
Set<String> keys = map.keySet();
// 增強 for
for (String k : keys) { System.out.println(k + "=" + map.get(k)); }
// 迭代器
Iterator<String> it = keys.iterator();
while (it.hasNext()) { String k = it.next(); System.out.println(k + "=" + map.get(k)); }
for (Map.Entry<String, Character> e : map.entrySet()) {
System.out.println(e.getKey() + "=" + e.getValue());
}
場景:分組統計,外層 Key 為組名,Value 為內層 Map(Person → 地址)。注意:Person 作為 Key 必須重寫 equals() 與 hashCode()。
Map<Map<Person, String>, String> groups = new LinkedHashMap<>();
groups.put(map1, "第一組");
groups.put(map2, "第二組");
// 遍歷
for (Entry<Map<Person, String>, String> outer : groups.entrySet()) {
String groupName = outer.getValue();
for (Entry<Person, String> inner : outer.getKey().entrySet()) {
System.out.println(groupName + ".." + inner.getKey() + ".." + inner.getValue());
}
}
List<String> list = new ArrayList<>(Arrays.asList("a","s","g","d"));
Collections.sort(list); // 自然順序排序
Collections.reverse(list); // 反轉
Collections.shuffle(list); // 隨機打亂
List<Integer> nums = new ArrayList<>();
Collections.addAll(nums, 1,2,3,4,5,7,8);
int idx = Collections.binarySearch(nums, 6); // -6 (插入點 = -idx-1)
集合核心無非增刪改查 + 遍歷。建議每個方法手敲 10 遍,構建肌肉記憶,面試手寫代碼零猶豫。