Reputation: 180
So, In my program I have a List<List<String>>
of strings.
For example:
List1: "Hi","Hello"
List2: "Fred","Bob"
List3: "how are you?","are you having a good day?","good weather, huh?"
could be the List<List<String>>
How can I generate a List<String>
of all possible sentences?
In this example, all sentences would be:
Hi Fred how are you?
Hi Fred are you having a good day?
Hi Fred good weather, huh?
Hi Bob how are you?
Hi Bob are you having a good day?
Hi Bob good weather, huh?
Hello Fred how are you?
Hello Fred are you having a good day?
Hello Fred good weather, huh?
Hello Bob how are you?
Hello Bob are you having a good day?
Hello Bob good weather, huh?
Upvotes: 0
Views: 71
Reputation: 3197
You can put all the List you have to a totalList, whose type is List < List < String > > . Combine 2 lists at a time to populate all of the combination cases.
Below is an exmaple for your reference, and it will print the information as you want.
Note: It supports dynamic number of List < List < String > > and dynamic size of List < String >.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> listOne = Arrays.asList("Hi","Hello");
List<String> listTwo = Arrays.asList("Fred","Bob");
List<String> listThree = Arrays.asList("how are you?","are you having a good day?","good weather, huh?");
List<List<String>> totalList = Arrays.asList(listOne,listTwo,listThree);
new Test().printAllCases(totalList);
}
public void printAllCases(List<List<String>> totalList)
{
List<String> result = new ArrayList<String>(totalList.get(0));
for(int index = 1; index < totalList.size() ; index++)
{
result = combineTwoLists(result, totalList.get(index));
}
/* print */
int count = 0;
for(String s: result)
{
System.out.printf("%d. %s\n", ++count, s);
}
}
private List<String> combineTwoLists(List<String> list1, List<String> list2)
{
List<String> result = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
for(String s1 : list1)
{
for(String s2: list2)
{
sb.setLength(0);
sb.append(s1).append(' ').append(s2);
result.add(sb.toString());
}
}
return result;
}
}
With your example, all posible case prints in Console are as follows:
1. Hi Fred how are you?
2. Hi Fred are you having a good day?
3. Hi Fred good weather, huh?
4. Hi Bob how are you?
5. Hi Bob are you having a good day?
6. Hi Bob good weather, huh?
7. Hello Fred how are you?
8. Hello Fred are you having a good day?
9. Hello Fred good weather, huh?
10. Hello Bob how are you?
11. Hello Bob are you having a good day?
12. Hello Bob good weather, huh?
Upvotes: 1
Reputation: 674
This is an excellent example of when to use recursion! Here are some helpful links to recursion if you are unfamiliar.
Upvotes: 1