【问题标题】:Generate string combinations from string arraylists stored in HashMap从存储在 HashMap 中的字符串数组列表生成字符串组合
【发布时间】:2011-11-16 16:17:05
【问题描述】:

我有一个java Hash,结构是这样的:

HashMap<Integer, ArrayList<String>> finalMap = new HashMap<Integer, ArrayList<String>>();

finalMap.toString() 是这样的

{0=[a1, a2, a3, a4], 1=[b1, b2, b3], 2=[c1, c2], 3=[d1]}

我需要像这样生成所有组合:

1. a1 b1 c1 d1
2. a1 b1 c2 d1
3. a1 b2 c1 d1
4. a1 b2 c2 d1
5. a1 b3 c1 d1
6. a1 b3 c2 d1
...
...
...
...
...

提前致谢。

【问题讨论】:

  • 在遍历 hashmap 时,我不明白如何遍历所有元素
  • 请发布您遇到问题的代码。一般来说,这里不欢迎在不付出努力的情况下寻求完整的解决方案。

标签: java string hashmap


【解决方案1】:

简单粗暴地遍历所有元素并跳过重复项(由 HashSet 自动完成)。有更好的方法来连接字符串,但要保持简单:

HashSet<String> result = new HashSet<String>();

for (String a : finalMap.get(0)) {
    for (String b : finalMap.get(1)) {
        for (String c : finalMap.get(2)) {
            for (String d : finalMap.get(3)) {
                result.add(a + b + c + d);
            }
        }
    }
}
System.out.println(result);  

输出应该类似于
[a3b2c1d1, a1b3c1d1, a1b1c1d1, a1b2c2d1, a4b1c2d1, a4b3c2d1, a1b2c1d1, a2b1c2d1, a2b2c2d1, a3b3c2d1, a1b1c2d1, a1b3c2d1, a2b3c2d1, a3b3c1d1, a2b2c1d1, a4b1c1d1, a4b3c1d1, a4b2c1d1, a3b1c2d1, a2b3c1d1, a3b1c1d1, a4b2c2d1, a2b1c1d1, a3b2c2d1]

但是,如果您还不知道列表的总数或者它们可能会有所不同,您可以使用递归方法

void generate(HashSet<String> resultList, String resultString,
        int listNum, HashMap<Integer, ArrayList<String>> data) {
    if (listNum == 0) {
        // start: begin a new resultString
        for (int i = 0; i < data.get(listNum).size(); i++) {
            generate(resultList, data.get(listNum).get(i), listNum + 1,
                    data);
        }
    } else if (listNum == data.size() - 1) {
        // end: store completed resultStrings
        for (int i = 0; i < data.get(listNum).size(); i++) {
            resultList.add(resultString + data.get(listNum).get(i));
        }
    } else {
        // middlepart: append current string to given resultString
        for (int i = 0; i < data.get(listNum).size(); i++) {
            generate(resultList, resultString + data.get(listNum).get(i),
                    listNum + 1, data);
        }
    }
}  

调用如下:

HashSet<String> result = new HashSet<String>();
generate(result2, null, 0, finalMap);
System.out.println(result);  

输出也应该像
[a3b2c1d1, a1b3c1d1, a1b1c1d1, a1b2c2d1, a4b1c2d1, a4b3c2d1, a1b2c1d1, a2b1c2d1, a2b2c2d1, a3b3c2d1, a1b1c2d1, a1b3c2d1, a2b3c2d1, a3b3c1d1, a2b2c1d1, a4b1c1d1, a4b3c1d1, a4b2c1d1, a3b1c2d1, a2b3c1d1, a3b1c1d1, a4b2c2d1, a2b1c1d1, a3b2c2d1]

【讨论】:

  • 这里我不知道有多少个数组,就像你给出的解决方案最多 4 个。
  • 我添加了一个递归解决方案,应该可以完成这项工作...... ps:不客气
猜你喜欢
  • 1970-01-01
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多