Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively traverse HashMap?

Tags:

java

algorithm

Is there a way to recursively traverse a HashMap so that value1 of key1 is actually the new key2 which returns value2 that again will be the next key3 and so on ... till it returns null? The logic is as follows:

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

I'm assuming this may be done through some recursion procedure? Please correct me if I were wrong. Thanks!

like image 782
Rock Avatar asked Jul 02 '26 07:07

Rock


1 Answers

Is this the one you wanted procedure? it will return the ultimate value by traversing the hashmap:

 Public Object traverseMap(Object key)
    while(hm.get(key) != null){
      key = hm.get(key);
    }
    return key;
 }
like image 171
C.c Avatar answered Jul 03 '26 20:07

C.c



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!