I have a List of List<String>‘s which I get from a external API method call:
List<List<String>> outerList
I have to create unique key combinations by concatenating strings from each list in the same order they are in the outer list.
Example: If outer list has 2 inner lists, say list1: {“A”,”B”} and list2: {“C”,”D”}. Then possible unique combinations will be AC, AD, BC and BD.
But the problem is the outerList size is dynamic, it can contain any number of inner lists. If the inner list numbers are fixed then I can write for loops and create combinations.
I am thinking in the direction of using reflections, recursion etc but so far have not been able to solve it.
public static void main(String[] args) {
List<List<String>> outerList = new ArrayList<List<String>>();
List<String> list1 = new ArrayList<String>();
list1.add("A");
list1.add("B");
List<String> list2 = new ArrayList<String>();
list2.add("C");
list2.add("D");
outerList.add(list1);
outerList.add(list2);
for(String s1: list1) {
for(String s2: list2) {
System.out.println(s1+s2);
}
}
}
Here outerList has 2 inner lists so I have created 2 for loops explicitly to iterate and concatenate. But in real-time outerList can have any number of inner lists, how to loop dynamically loop through all the inner loops and concatenate?
This code works for me:
Output: