递归迭代hashmap [英] recursive iterate hashmap

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

问题描述

我想从hashmap中检索k,v对。
entrys是这样的:

i want to retrieve k,v-pairs from a hashmap. the entrys are like this:

a = 3,4 
b = 5,6

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

and so on. i need combinations of these values.

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

我不知道有多少个键以及多少个值。与入口集我可以得到的价值,但不是组合。它看起来像递归,但如何?

I don't know how many keys and how many entrys the values have. with entryset i can get the values but not combinations. it looks like recursion but how?

这是我的代码:

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


推荐答案

您可以尝试以下代码:

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 在递归情况下。

No guarantees on memory efficiency or speed. If you want to preserve the order of the keys in the map, you will have to pass in a TreeMap and change the code to use a TreeMap under the recursive case.

根据基本情况,我假设您至少在地图中有一个条目。

As the base case suggests, I'm assuming you have at least one entry in your map.

这篇关于递归迭代hashmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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