EYA Behi:
私はTreeMapのと呼ばれるmapDependeciesを持っています。
TreeMap<String, ArrayList<String>> mapDep
私のマップの例:
[a=[b, c], c=[f,e], b=[], f=[x,y]
各キー(例えばA)は、それの値(B、C)から依存ので。私はそれの依存関係、および配列内のそれらの依存関係を持つキーを載せていきたいと思います。
私は次のように結果になりたいです:
Array = [[a,b,c,f,x,y,e], [c,f,x,y,e], b[], [f,x,y]]
どのように私は結果が欲しかっ取得する再帰を使用することができますか?
azro:
あなたは何度も何度も依存関係を取得するには、再帰が必要なので、何度も何度もメソッドを呼び出します。
static List<String> getDeps(TreeMap<String, ArrayList<String>> mapDep, String key) {
List<String> res = new ArrayList<>(Collections.singletonList(key));
if (mapDep.containsKey(key)) {
for (String val : mapDep.get(key)) {
res.addAll(getDeps(mapDep, val)); // call again with new key from V
}
}
return res;
}
使い方
List<List<String>> result = new ArrayList<>();
for (String key : mapDep.keySet()) {
result.add(getDeps(mapDep, key));
}
System.out.println(result); //[[a, b, c, f, x, y, e], [b], [c, f, x, y, e], [f, x, y]]