2

kから, -vペアを取得したいHashMap。エントリは次のようになります。

a = 3,4
b = 5,6

等々。これらの値の組み合わせが必要です。

a=3, b=5
a=3, b=6
a=4, b=5
a=4, b=6

キーの数と値のエントリ数がわかりません。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 (Map.Entry<String, String[]> entry : map.entrySet()) {
    for (String value : entry.getValue()) {
        System.out.println(entry.getKey() + ": " + value);
    }
}
file.close();
4

3 に答える 3

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 + ", ");
        }
    }
}

メモリ効率や速度を保証するものではありません。マップ内のキーの順序を保持したい場合は、a を渡して、再帰ケースでTreeMapa を使用するようにコードを変更する必要があります。TreeMap

基本ケースが示唆するように、マップに少なくとも 1 つのエントリがあると想定しています。

于 2011-03-16T10:25:04.100 に答える