How do I generate a Cartesian product in Java?
Asked Answered
B

7

10

I have a number of ArrayList with each ArrayList having objects and each one can have different length. I need to generate permutation like in the below example:

Suppose I have 2 ArrayList:

ArrayList A has object a, object b and object c
ArrayList B has object d, object e

Then the output should be 6 new ArrayList with these combinations:

Combination 1 object a and object d,
Combination 2 object a and object e,
Combination 3 object b and object d,
Combination 4 object b and object e,
Combination 5 object c and object d,
Combination 6 object c and object e,

Can anyone help me?

Bracket answered 10/11, 2011 at 16:13 Comment(0)
F
5

With Java8 streams

List<String> a = Arrays.asList("a", "b", "c");
List<String> b = Arrays.asList("d", "e");
String[][] AB = a.stream()
        .flatMap(ai -> b.stream()
                .map(bi -> new String[]{ai, bi}))
        .toArray(String[][]::new);
System.out.println(Arrays.deepToString(AB));

output

[[a, d], [a, e], [b, d], [b, e], [c, d], [c, e]]

To get as List

List<List<String>> ll = a.stream()
        .flatMap(ai -> b.stream()
                .map(bi -> new ArrayList<>(Arrays.asList(ai, bi))))
        .collect(Collectors.toList());
Fictile answered 23/10, 2016 at 12:8 Comment(0)
F
5

Guava 19+

Lists.cartesianProduct(List...)

E.g.:

List<Object> list1 = Arrays.asList("a", "b", "c");
List<Object> list2 = Arrays.asList("d", "e");
System.out.println(Lists.cartesianProduct(list1, list2));

Output:

[[a, d], [a, e], [b, d], [b, e], [c, d], [c, e]]
Flexile answered 4/12, 2016 at 9:56 Comment(0)
I
4

With an Iterable+Iterator:

import java.util.*;

class CartesianIterator <T> implements Iterator <List <T>> {

    private final List <List <T>> lilio;    
    private int current = 0;
    private final long last;

    public CartesianIterator (final List <List <T>> llo) {
        lilio = llo;
        long product = 1L;
        for (List <T> lio: lilio)
            product *= lio.size ();
        last = product;
    } 

    public boolean hasNext () {
        return current != last;
    }

    public List <T> next () {
        ++current;
        return get (current - 1, lilio);
    }

    public void remove () {
        ++current;
    }

    private List<T> get (final int n, final List <List <T>> lili) {
        switch (lili.size ())
        {
            case 0: return new ArrayList <T> (); // no break past return;
            default: {
                List <T> inner = lili.get (0);
                List <T> lo = new ArrayList <T> ();
                lo.add (inner.get (n % inner.size ()));
                lo.addAll (get (n / inner.size (), lili.subList (1, lili.size ())));
                return lo;
            }
        }
    }
}

class CartesianIterable <T> implements Iterable <List <T>> {

    private List <List <T>> lilio;  

    public CartesianIterable (List <List <T>> llo) {
        lilio = llo;
    }

    public Iterator <List <T>> iterator () {
        return new CartesianIterator <T> (lilio);
    }
}

You can use them in a simplified for-loop:

class CartesianIteratorTest {

    public static void main (String[] args) {
        List <Character> la = Arrays.asList (new Character [] {'a', 'b', 'c'});
        List <Character> lb = Arrays.asList (new Character [] {'d', 'e'});      
        List <List <Character>> llc = new ArrayList <List <Character>> ();
        llc.add (la);
        llc.add (lb);

        CartesianIterable <Character> ci = new CartesianIterable <Character> (llc);
        for (List<Character> lo: ci)
            show (lo);
    }

    public static void show (List <Character> lo) {
        System.out.print ("(");
        for (Object o: lo)
            System.out.print (o);
        System.out.println (")");
    }
}
Interstratify answered 10/4, 2012 at 6:23 Comment(0)
J
2

Cartesian product of multiple lists using the map and reduce approach

  • The map method represents each element of the list as a singleton list and specifies the format of the result.

    Intermediate output:

    [[a], [b], [c]]
    [[d], [e]]
    [[f]]
    
  • The reduce method sums pairs of 2D lists into a single 2D list.

    Final output:

    [[a, d, f], [a, e, f], [b, d, f], [b, e, f], [c, d, f], [c, e, f]]
    

Try it online!

public static void main(String[] args) {
    List<String> a = Arrays.asList("a", "b", "c");
    List<String> b = Arrays.asList("d", "e");
    List<String> c = Arrays.asList("f");

    List<List<String>> cp = cartesianProduct(Arrays.asList(a, b, c));
    // output
    System.out.println(cp);
}
public static <T> List<List<T>> cartesianProduct(List<List<T>> lists) {
    // check if not null
    if (lists == null) return null;
    // cartesian product of multiple lists
    return lists.stream()
            // only those lists that are not null and not empty
            .filter(list -> list != null && list.size() > 0)
            // represent each list element as a singleton list
            .map(list -> list.stream().map(Collections::singletonList)
                    // Stream<List<List<T>>>
                    .collect(Collectors.toList()))
            // intermediate output
            .peek(System.out::println)
            // stream of lists into a single list
            .reduce((lst1, lst2) -> lst1.stream()
                    // combinations of inner lists
                    .flatMap(inner1 -> lst2.stream()
                            // concatenate into a single list
                            .map(inner2 -> Stream.of(inner1, inner2)
                                    .flatMap(List::stream)
                                    .collect(Collectors.toList())))
                    // list of combinations
                    .collect(Collectors.toList()))
            // otherwise an empty list
            .orElse(Collections.emptyList());
}

See also: Cartesian product of an arbitrary number of sets

Jeanettajeanette answered 10/11, 2011 at 16:14 Comment(0)
B
0

Cartesian product of multiple lists

You can use the reduce method with three parameters:

  • identity - specify the result stub.

    List<List<T>>
    
  • accumulator - append elements of lists to the result.

    List<List<T>> result, List<T> list
    
  • combiner - is used in parallel mode, combines the results.

    List<List<T>> result1, List<List<T>> result2
    

Try it online!

/**
 * @param lists the lists for multiplication
 * @param <T>   the type of list element
 * @return the Cartesian product
 */
public static <T> List<List<T>> cartesianProduct(List<List<T>> lists) {
    // check if incoming data is not null
    if (lists == null) return Collections.emptyList();
    return lists.stream()
        // non-null and non-empty lists
        .filter(list -> list != null && list.size() > 0)
        // stream of lists into a single list
        .reduce(// identity - specify the result stub
                Collections.singletonList(Collections.emptyList()),
                // accumulator - append elements of lists to the result
                (result, list) -> result.stream()
                        .flatMap(inner -> list.stream()
                                .map(el -> {
                                    List<T> nList = new ArrayList<>(inner);
                                    nList.add(el);
                                    return nList;
                                }))
                        // list of combinations
                        .collect(Collectors.toList()),
                // combiner - is used in parallel mode, combines the results
                (result1, result2) -> {
                    result1.addAll(result2);
                    return result1;
                });
}
public static void main(String[] args) {
    List<String> l1 = Arrays.asList("A", "B");
    List<String> l2 = Arrays.asList("C", "D");
    List<String> l3 = Arrays.asList("E", "F");

    List<List<String>> cp = cartesianProduct(Arrays.asList(l1, l2, l3));
    // output
    System.out.println(cp);
}

Output:

[[A,C,E],[A,C,F],[A,D,E],[A,D,F],[B,C,E],[B,C,F],[B,D,E],[B,D,F]]

See also: Cartesian product of 3 collections

Bohemianism answered 10/11, 2011 at 16:14 Comment(0)
D
0

Use Guava... Here is an example of a Cartesian product of a list with itself:

public static void main(String[] args) {
  //How to do a cartesian product of a List of items
  List<Integer> listToSelfMultiply = Arrays.asList(
      new Integer(1), new Integer(2), new Integer(3), new Integer(4));
  LinkedList<Integer> linkedListCopy = Lists.newLinkedList(listToSelfMultiply);
  for (Integer i : listToSelfMultiply) {
    if (linkedListCopy.size() == 1) {
      break;
    }
    linkedListCopy.remove();
    System.out.println("" + Arrays.deepToString(
        Lists.cartesianProduct(Arrays.asList(i), linkedListCopy).toArray()) + "");
    }
}
Dejong answered 29/10, 2018 at 15:45 Comment(0)
A
-1

Use nested for loops that would have a loop for every ArrayList as below. I am assuming I have two ArrayLists - intList and stringList. I can have two nested for loops (one for each list) to generate the permutation.

for (Integer i : intList) {
    for (String s : stringList) {
        ...
    }
}
Anzac answered 10/11, 2011 at 16:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.