Skip to content
Advertisement

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

Given

JavaScript

How do I programmatically achieve:

JavaScript

with

JavaScript

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:

JavaScript

Test:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement