Skip to content
Advertisement

java – creating 2D array (matrix) from two 1D arrays

Given

public Object[] suite = {"diamonds","hearts","clubs","spades"};
public Object[] rank  = {"J","Q","K","A"};

How do I programmatically achieve:

Object[][] card = {{"J","diamonds"},{"Q","diamonds"},{"K","diamonds"},{"A","diamonds}
                  ,{"J","hearts"},  {"Q","hearts"},  {"K","hearts"},  {"A","hearts"}
                  ,{"J","clubs"},   {"Q","clubs"},   {"K","clubs"},   {"A","clubs"}
                  ,{"J","spades"},  {"Q","spades"},  {"K","spades"},  {"A","spades"}
                  };

with

public Object[][] someMagic( Object[] suite, Object[] rank) {
    Object[][] retVal = new Object[suite.length][rank.length]
    // insert magic here
    return retVal;
}

Yes everything needs to be Object, Object[] or Object[][] due to upstream constraints ie. TestNG @DataProvider.

Advertisement

Answer

A couple of nested loops does the magic but the dimensions of the retVal are different:

public Object[][] someMagic(Object[] suite, Object[] rank) {
    Object[][] retVal = new Object[suite.length * rank.length][];
    int i = 0;
    for (Object s : suite) {
        for (Object r : rank) {
            retVal[i++] = new Object[]{ r, s };
        }
    }
    return retVal;
}

Test:

Object[] suite = {"diamonds","hearts","clubs","spades"};
Object[] rank  = {"J","Q","K","A"};
System.out.println(Arrays.deepToString(someMagic(suite, rank)));

Output (not pretty-printed):

[[J, diamonds], [Q, diamonds], [K, diamonds], [A, diamonds], [J, hearts], [Q, hearts], [K, hearts], [A, hearts], [J, clubs], [Q, clubs], [K, clubs], [A, clubs], [J, spades], [Q, spades], [K, spades], [A, spades]]


However, the shorter spell may be cast using Stream API and Stream::flatMap in particular:

public static Object[][] someMagic(Object[] suite, Object[] rank) {
    return Arrays.stream(suite)
        .flatMap(s -> Arrays.stream(rank).map(r -> new Object[]{ r, s }))
        .toArray(Object[][]::new);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement