Eya Behi :
I have a TreeMap called mapDependecies :
TreeMap<String, ArrayList<String>> mapDep
example of my map :
[a=[b, c], c=[f,e], b=[], f=[x,y]
So each key (example a) depends from it's values (b,c). I want to put the key with it's dependencies, and their dependencies in an Array.
I want the result to be as follows :
Array = [[a,b,c,f,x,y,e], [c,f,x,y,e], b[], [f,x,y]]
How can I use recursion to get the result wanted?
azro :
You need recursion, to get the dependencies again and again, so call the method again and again :
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;
}
Using
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]]
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=350137&siteId=1