递归迭代hashmap

zya*_*mat 2 java recursion hashmap

我想从散列图中检索k,v对.这些托管是这样的:

a = 3,4 
b = 5,6
Run Code Online (Sandbox Code Playgroud)

等等.我需要这些值的组合.

a=3, b=5. 
a=3, b=6.
a=4, b=5.
a=4, b=6.
Run Code Online (Sandbox Code Playgroud)

我不知道有多少个键和多少个值.使用entryset我可以得到值而不是组合.它看起来像递归,但如何?

这是我的代码:

HashMap<String, String[]> map = new HashMap<String, String[]>();

BufferedReader file = new BufferedReader(new FileReader("test.txt"));
String str;


while ((str = file.readLine()) != null) { 


    ... logic


    map.put(key, value);



}
System.out.println("number of keys: " + map.size());
for(Entry<String, String[]> entry : map.entrySet()) {
    for(String value : entry.getValue()) {
        System.out.println(entry.getKey() + ": " + value);
    }
}
file.close();
Run Code Online (Sandbox Code Playgroud)

mas*_*ime 5

您可以尝试以下代码:

public void mapPermute(Map<String, String[]> map, String currentPermutation) {
    String key = map.keySet().iterator().next(); // get the topmost key

    // base case
    if (map.size() == 1) {          
        for (String value : map.get(key)) {
            System.out.println(currentPermutation + key + "=" + value);
        }
    } else {
        // recursive case
        Map<String, String[]> subMap = new HashMap<String, String[]>(map);

        for (String value : subMap.remove(key)) {
            mapPermute(subMap, currentPermutation + key + "=" + value + ", ");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

无法保证内存效率或速度.如果要保留映射中键的顺序,则必须传入TreeMap并更改代码以TreeMap在递归情况下使用a .

如基本情况所示,我假设您的地图中至少有一个条目.