I have a List<List<String>>
I need to get a List of all possible concatenation on the first dimension
[ [1,2 ], [1] , [3,4] ]
should give:
[ 113, 114, 213, 214 ]
I’m trying with 2 loops, like it should be possible to.
This is what I have tried:
private static List<String> constructIndexes(List<List<String>> indexList){
List<String> index = new ArrayList<String>();
String v="";
for (int i=0; i< indexList.size(); i++){
List<String> l = indexList.get(i);
for (int j=0; j<l.size(); j++){
if (index.size()>0){
for (int k=0; k<index.size(); k++){
index.set(k, index.get(k)+l.get(j));
// System.out.println(">");
}
} else {
index.add(l.get(j));
}
}
}
return index;
}
some init code:
List<List<String>> indexList = new ArrayList<List<String>>();
List<String> l = new ArrayList<String>();
l.add("1");
l.add("2");
indexList.add(l);
l = new ArrayList<String>();
l.add("1");
indexList.add(l);
l = new ArrayList<String>();
l.add("3");
l.add("4");
indexList.add(l);
System.out.println( constructIndexes(indexList));
Since the number of lists in the outer list (i.e. the list of lists) is not known until the runtime, you cannot know the number of the loops upfront. In situations like this, you need a recursive solution:
Here is how to call it: