数据库中结构及数据如下:id parentId001 003
003 005
004 002
005 010
010 020需要求出某个ID的父节点的最终路径:例如对于ID为“001”的数据来说,其中路径为:001-》003-》005-》010-》020,最后输出:020/010/005/001,用java实现,

解决方案 »

  1.   

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.TreeMap;public class Test
    {
    Map<String, String> map = new TreeMap<String, String>(); static List<String> list = new ArrayList<String>(); String[] ids = { "001", "003", "004", "005", "010" }; String[] parentIds = { "003", "005", "002", "010", "020" };

    static String value = ""; public void putInto()
    {
    for (int i = 0; i < 5; i++)
    {
    map.put(ids[i], parentIds[i]);
    }
    }
    public void concrete(String id)
    {
    list.add(id); Set s = map.entrySet(); String parentId = map.get(id);

    for (Iterator inter = s.iterator(); inter.hasNext();)
    {
    Map.Entry me = (Map.Entry)inter.next();

                            String key = (String)me.getKey(); value = (String)me.getValue(); if (key.equals(parentId))
    {
    concrete(parentId);
    }
    }
    }
    public static void main(String[] args)
    {
    Test t = new Test(); t.putInto(); t.concrete("001"); list.add(value); for (int i = list.size()-1; i >= 0; i--)
    {
    System.out.print(list.get(i)); if(i != 0)
    {
    System.out.print(" ==> ");
    }
                    }
    }
    }
    看看这样符合要求么?