问题:
public static void main(String[] args) {
List<List<String>> source = new ArrayList<>();
source.add(Lists.newArrayList("a"));
source.add(Lists.newArrayList("b","c"));
source.add(Lists.newArrayList("d","e"));
//实现结果组合为: [a_b_d, a_b_e, a_c_d, a_c_e]
}
方法一:
public static List<String> sort (List<List<String>> source,List<String> tag,List<String> handle){
if(CollectionUtils.isEmpty(source) && CollectionUtils.isEmpty(handle)){
return tag;
}
if(CollectionUtils.isEmpty(tag)){
List<String> first = source.remove(0);
List<String> second = source.remove(0);
for (String firstNum: first) {
for (String secondNum: second) {
tag.add(firstNum+"_"+secondNum);
}
}
}else{
List<String> tagNew = new ArrayList<>();
for (int i = 0; i < tag.size(); i++) {
String value = tag.get(i);
for (int j = 0; j < handle.size(); j++) {
tagNew.add(value+"_"+handle.get(j));
}
}
tag = tagNew;
}
if(CollectionUtils.isEmpty(source)){
return tag;
}
return sort(source,tag,source.remove(0));
}
测试代码:
public static void main(String[] args) {
List<List<String>> source = new ArrayList<>();
source.add(Lists.newArrayList("a"));
source.add(Lists.newArrayList("b","c"));
source.add(Lists.newArrayList("d","e"));
List<String> sort = sort(source, new ArrayList<>(), new ArrayList<>());
System.out.println(sort);
}
方法二:
public static void main(String[] args) {
List<String> l1 = Arrays.asList("a");
List<String> l2 = Arrays.asList("b", "c");
List<String> l3 = Arrays.asList("d", "e");
Collection<Collection<String>> a = Arrays.asList(l1,l2, l3);
List<List<String>> tmp = new ArrayList<>();
List<List<String>> newTmp = new ArrayList<>();
Iterator<Collection<String>> iterator = a.iterator();
while (iterator.hasNext()) {
aaa(iterator, tmp, newTmp);
tmp.clear();
tmp.addAll(newTmp);
newTmp.clear();
}
System.out.println(tmp);
}
private static void aaa(Iterator<Collection<String>> iterator, List<List<String>> tmp,List<List<String>> newTmp) {
Collection<String> next = iterator.next();
for (String value : next) {
if (tmp.isEmpty()) {
newTmp.add(Arrays.asList(value));
}
for (List<String> oldValue : tmp) {
List<String> valueList = new ArrayList<String>(oldValue);
valueList.add(value);
newTmp.add(valueList);
}
}
}