Recursively pass a HashMap?

Is there a way to recursively traverse HashMap, so value1of key1is actually a new key2one that returns value2, which will again be next key3and so on ... until it returns null? The logic is this:

hm.get(key)
hm.get(hm.get(key))
hm.get(hm.get(hm.get(key)))
......

I suppose this can be done through some recursion procedure? Please correct me if I am wrong. Thank!

+3
source share
3 answers

Is this the one you need? it will return the final value by going through the hash map:

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

(.. , ), . , :

Object key = someInitialKey;
Object value = null;
do {
  value = hm.get( key );
  key = value;
} while( value != null );
+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 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);
    }
}
+1

All Articles