对于数据结构中的父子关系(一父一子),用map模拟如下,10的父亲是11,11的父亲是12,12的父亲是13,假如要找到10的曾祖父(13),可用下面的算法 

 

import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.bidimap.DualHashBidiMap;
import org.junit.Test;

@Test
 public void testCascadRelation() {
  Map<String, String> map = new HashMap<String, String>();
  map.put("10", "11");
  map.put("11", "12");
  map.put("12", "13");
  map.put("20", "21");
  map.put("21", "22");
  map.put("30", "31");
  map.put("31", "31");
  map.put("40", null);

  BidiMap resultMap =  new DualHashBidiMap();
  for(String key : map.keySet() ) {
   Object orgKey = resultMap.getKey(key);
   Object orgValue = resultMap.get(map.get(key));
   if (orgKey != null) {
    resultMap.put(orgKey, map.get(key));
   } else if (orgValue != null) {
    resultMap.put(key, orgValue);

   } else {
    resultMap.put(key, map.get(key));
   }
  }

  System.out.println("resultMap:"+resultMap);

 }

结果:

resultMap:{20=22, 10=13, 30=31, 40=null}