集合框架(List、Set、Map)是 Java 核心基礎,靈活運用其特性(去重、隨機存取、鍵值映射)能優雅解決許多演算法題目。本文精選兩道經典練習,示範「大問題拆解為小問題」的思維與 HashSet/ArrayList/StringBuilder 組合拳實戰。
字元池:a-z、A-Z、0-9(共 62 個字元)
ArrayList<Character>public static ArrayList<Character> getContainer() {
ArrayList<Character> pool = new ArrayList<>();
for (char c = 'a'; c <= 'z'; c++) pool.add(c);
for (char c = 'A'; c <= 'Z'; c++) pool.add(c);
for (char c = '0'; c <= '9'; c++) pool.add(c);
return pool; // size = 62
}
HashSet 去重)public static String getRandomString(ArrayList<Character> pool) {
HashSet<Character> chars = new HashSet<>();
while (chars.size() < 10) {
int idx = (int) (Math.random() * pool.size());
chars.add(pool.get(idx)); // Set 自動去重
}
StringBuilder sb = new StringBuilder();
for (Character c : chars) sb.append(c);
return sb.toString();
}
public static ArrayList<String> getRandomStrings(ArrayList<Character> pool) {
HashSet<String> set = new HashSet<>();
while (set.size() < 10) set.add(getRandomString(pool));
return new ArrayList<>(set); // 轉 List 便於遍歷
}
public static void main(String[] args) {
ArrayList<Character> pool = getContainer();
ArrayList<String> result = getRandomStrings(pool);
result.forEach(System.out::println);
}
HashSet<Character> 去重public static String getRandomNumStr() {
HashSet<Character> set = new HashSet<>();
while (set.size() < 8) {
int n = (int) (Math.random() * 10); // 0-9
set.add((char) ('0' + n));
}
StringBuilder sb = new StringBuilder();
set.forEach(sb::append);
return sb.toString();
}
StringBuilder + contains() 判重public static String getRandomNumStrSB() {
StringBuilder sb = new StringBuilder();
while (sb.length() < 8) {
int n = (int) (Math.random() * 10);
if (!sb.toString().contains(String.valueOf(n))) {
sb.append(n);
}
}
return sb.toString();
}
public static HashSet<String> getFourUnique() {
HashSet<String> set = new HashSet<>();
while (set.size() < 4) set.add(getRandomNumStrSB());
return set;
}
Map 實現「隨機編號 → 商品名」映射public static void main(String[] args) {
String[] goods = {"可樂", "啤酒", "烤鴨", "蒼老師"};
HashSet<String> codes = getFourUnique();
ArrayList<String> codeList = new ArrayList<>(codes); // 有序化
Map<String, String> catalog = new LinkedHashMap<>(); // 保持插入順序
for (int i = 0; i < goods.length; i++) {
catalog.put(codeList.get(i), goods[i]);
}
catalog.forEach((k, v) -> System.out.println(k + " : " + v));
}
輸出範例:
38472910 : 可樂 19283746 : 啤酒 56473829 : 烤鴨 01928374 : 蒼老師
| 需求 | 推薦集合/技巧 | 理由 |
|---|---|---|
| 元素去重 | HashSet | O(1) 平均插入/查找,自動過濾重複 |
| 隨機抽取 | ArrayList + Math.random() * size | 支援索引隨機存取 |
| 字串拼接 | StringBuilder | 避免 String += 產生大量中間物件 |
| 保持插入順序 | LinkedHashMap / LinkedHashSet | 兼具去重與順序 |
| Set → List 轉換 | new ArrayList<>(set) | 一行程式碼完成,便於索引遍歷 |
這兩道題目雖簡單,卻涵蓋了集合框架最核心的使用模式:容器選擇 → 去重策略 → 隨機存取 → 類型轉換 → 業務映射。熟練掌握這套組合拳,面對實務開發中的資料處理需求將遊刃有餘。