如何创建两个或多个字符串数组列表的排列和组合到一个组合列表中

问题描述 投票:-1回答:1

我想获得多个字符串arraylist的所有组合

String arr1[]={"red","green"}
String arr2[]={"underline"}
ArrayList a=get_Combination(arr1,arr2)

输入:

array 1=["red","green","blue"].
array 2=["bold"].
array 3=["underline"].`

输出:组合列表应如下所示

[[red],[red,bold],[red,bold,underline],[underline],[underline,bold].......]
java string combinations permutation
1个回答
0
投票

这是你想要的吗?

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class Combin {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        final String[][] array = new String[][] {
            new String[] {"red","green","blue"}
            , new String[] {"bold"}
            , new String[] {"underline"}
        };

        final List<String> list = combination(Arrays.asList(array));

        list.stream()
        .forEach(
            System.out::println
        )
        ;
    }

    static List<String> combination(
            final List<String[]> array)
    {
        if(array == null || array.size() < 1) {
            return Collections.<String>emptyList();
        }

        if(array.size() == 1) {
            return Arrays.stream(array.get(0))
                    .collect(Collectors.toList())
                    ;
        }

        if(array.size() == 2) {
            List<String> list1 = Arrays.stream(array.get(0))
                                .collect(Collectors.toList())
                                ;

            List<String> list2 = Arrays.stream(array.get(1))
                                .collect(Collectors.toList())
                                ;

            final List<String> list3 = new ArrayList<>();
            list1.stream()
            .forEach(
                s1 -> {
                    list2.stream()
                    .forEach(
                        s2 -> {
                            list3.add(s1 + ", " + s2);
                        }
                    );
                }
            )
            ;

            final List<String> list = new ArrayList<>();
            list.addAll(list1);
            list.addAll(list2);
            list.addAll(list3);

            return list;
        }

        //length > 2
        List<String> list = combination(array.subList(0, 2));

        for(int i=2; i<array.size(); i++) {
            List<String[]> newArrayList = new ArrayList<>();
            newArrayList.add(list.toArray(new String[list.size()]));
            newArrayList.add(array.get(i));

            list = combination(newArrayList);
        }

        return list;

    }
}

结果:

red
green
blue
bold
red, bold
green, bold
blue, bold
underline
red, underline
green, underline
blue, underline
bold, underline
red, bold, underline
green, bold, underline
blue, bold, underline
© www.soinside.com 2019 - 2024. All rights reserved.