首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 集合框架經典練習題:不重複隨機字串與數字生成

     編輯:Java 相關知識

集合框架(List、Set、Map)是 Java 核心基礎,靈活運用其特性(去重、隨機存取、鍵值映射)能優雅解決許多演算法題目。本文精選兩道經典練習,示範「大問題拆解為小問題」的思維與 HashSet/ArrayList/StringBuilder 組合拳實戰。


題目一:生成 10 個長度 10、字元不重複、字串互不相同的隨機字串

字元池:a-z、A-Z、0-9(共 62 個字元)

步驟 1:建立字元容器 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
}

步驟 2:單一字串生成(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();
}

步驟 3:生成 10 個不重複字串

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);
}

題目二:生成 4 個 8 位數字、數字不重複、字串互不相同的隨機字串

方法一: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();
}

生成 4 個不重複字串

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 : 蒼老師

核心技巧總結

需求推薦集合/技巧理由
元素去重HashSetO(1) 平均插入/查找,自動過濾重複
隨機抽取ArrayList + Math.random() * size支援索引隨機存取
字串拼接StringBuilder避免 String += 產生大量中間物件
保持插入順序LinkedHashMap / LinkedHashSet兼具去重與順序
Set → List 轉換new ArrayList<>(set)一行程式碼完成,便於索引遍歷

這兩道題目雖簡單,卻涵蓋了集合框架最核心的使用模式:容器選擇 → 去重策略 → 隨機存取 → 類型轉換 → 業務映射。熟練掌握這套組合拳,面對實務開發中的資料處理需求將遊刃有餘。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved