Cartesian product of arbitrary sets in Java

后端 未结 9 2238
小鲜肉
小鲜肉 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:40

    Edit: Previous solutions for two sets removed. See edit history for details.

    Here is a way to do it recursively for an arbitrary number of sets:

    public static Set> cartesianProduct(Set... sets) {
        if (sets.length < 2)
            throw new IllegalArgumentException(
                    "Can't have a product of fewer than two sets (got " +
                    sets.length + ")");
    
        return _cartesianProduct(0, sets);
    }
    
    private static Set> _cartesianProduct(int index, Set... sets) {
        Set> ret = new HashSet>();
        if (index == sets.length) {
            ret.add(new HashSet());
        } else {
            for (Object obj : sets[index]) {
                for (Set set : _cartesianProduct(index+1, sets)) {
                    set.add(obj);
                    ret.add(set);
                }
            }
        }
        return ret;
    }
    
    
    

    Note that it is impossible to keep any generic type information with the returned sets. If you knew in advance how many sets you wanted to take the product of, you could define a generic tuple to hold that many elements (for instance Triple), but there is no way to have an arbitrary number of generic parameters in Java.

    提交回复
    热议问题