递归遍历HashMap?

时间:2012-05-01 06:49:22

标签: java algorithm

有没有办法以递归方式遍历HashMap,以便value1 key1实际上是key2新的value2,它将再次返回key3下一个null等等......直到它返回hm.get(key) hm.get(hm.get(key)) hm.get(hm.get(hm.get(key))) ...... ?逻辑如下:

{{1}}

我假设这可以通过一些递归程序来完成?如果我错了,请纠正我。谢谢!

3 个答案:

答案 0 :(得分:2)

这是你想要的程序吗?它将通过遍历hashmap返回最终值:

 Public Object traverseMap(Object key)
    while(hm.get(key) != null){
      key = hm.get(key);
    }
    return key;
 }

答案 1 :(得分:1)

如果以这种方式设置散列映射(即它包含一个也是另一个值的键的值),那么它是可能的。您可以在递归方法中执行此操作,但循环就足够了:

Object key = someInitialKey;
Object value = null;
do {
  value = hm.get( key );
  key = value;
} while( value != null );

答案 2 :(得分:1)

嗯,无论如何,那是你要求的(尾巴!)递归版本:

public class Qsdf {

    public static Object traverseMap(Map m, Object key) {
        return traverseMap(m, key, new HashSet());
    }

    public static Object traverseMap(Map m, Object key, Set traversed) {
        if (key == null) { // first key has to be null
            throw new NullPointerException();
        }
        traversed.add(key);
        Object value = m.get(key);
        if (traversed.contains(value)) { // added after Stephen C's comment on other answer
            // cycle found, either throw exception, return null, or return key
            return key;
        }
        return value != null ?
                traverseMap(m, value, traversed) :
                key; // I guess you want to return the last value that isn't also a key
    }

    public static void main(String[] args) {
        final HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
        m.put(0, 1);
        m.put(1, 2);
        m.put(3, 4);
        m.put(2, 3);
        final Object o = traverseMap(m, 0);
        System.out.println(o);
    }
}