Cartesian product of arbitrary sets in Java

后端 未结 9 2030
小鲜肉
小鲜肉 2020-11-22 07:28

Do you know some neat Java libaries that allow you to make cartesian product of two (or more) sets?

For example: I have three sets. One with objects of class Person

相关标签:
9条回答
  • 2020-11-22 07:52

    The method below creates the cartesian product of a list of list of strings:

    protected <T> List<List<T>> cartesianProduct(List<List<T>> lists) {
        List<List<T>> resultLists = new ArrayList<List<T>>();
        if (lists.size() == 0) {
            resultLists.add(new ArrayList<T>());
            return resultLists;
        } else {
            List<T> firstList = lists.get(0);
            List<List<T>> remainingLists = cartesianProduct(lists.subList(1, lists.size()));
            for (T condition : firstList) {
                for (List<T> remainingList : remainingLists) {
                    ArrayList<T> resultList = new ArrayList<T>();
                    resultList.add(condition);
                    resultList.addAll(remainingList);
                    resultLists.add(resultList);
                }
            }
        }
        return resultLists;
    }
    

    Example:

    System.out.println(cartesianProduct(Arrays.asList(Arrays.asList("Apple", "Banana"), Arrays.asList("Red", "Green", "Blue"))));
    

    would yield this:

    [[Apple, Red], [Apple, Green], [Apple, Blue], [Banana, Red], [Banana, Green], [Banana, Blue]]
    
    0 讨论(0)
  • 2020-11-22 08:00

    how about using odl.com.google.common18.collect.Sets and calling Sets.cartesianProduct() method

    0 讨论(0)
  • 2020-11-22 08:01

    This is a pretty old question, but why not use Guava's cartesianProduct?

    0 讨论(0)
提交回复
热议问题