递归或迭代地从HashMap检索键值组合 [英] Recursively or iteratively retrieve key-value combinations from a HashMap

查看:70
本文介绍了递归或迭代地从HashMap检索键值组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从HashMap检索kv-对。 入口如下:

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

推荐答案

您可以尝试以下代码:

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

不保证内存效率或速度。如果希望保持键在映射中的顺序,则必须传入TreeMap,并在递归情况下更改代码以使用TreeMap

如基本情况所示,我假设您的映射中至少有一个条目。

这篇关于递归或迭代地从HashMap检索键值组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆