The purpose is to create a NxM matrix from an array of strings, ex:
String[] arrayOfStrings = new String[] {"1 2 3","4 5 6"}
Then the output matrix would be
Integer[][] matrix = new Integer[][] { {1,2,3},{4,5,6}}
The transformer should be generic enough that it can produce a matrix of Double, Integer…
for 1 dimension I was able to do it. Here is the code:
/** * Construct a matrix row from string line * Example: * in = "1.7 5.14 9" * out = new Double[] { 1.7 ,5.14,9} * * @param in string to lineToRow * @param compatibleParser specialize parser * @param <E> type * @return matrix row */ public static <E> E[] lineToRow(String in, Function<String, E> compatibleParser) { final String[] els = in.split(" +"); /* ignore multiple spaces */ final E[] res = (E[]) new Object[els.length]; int i = 0; for (String s : els) { res[i] = compatibleParser.apply(s); i++; } return res; }
and the test for it is like following:
@Test public void stringLineToMatrixRow() { String line0 = "1 2 3"; Assert.assertArrayEquals(new Integer[]{1, 2, 3}, MatrixUtils.lineToRow(line0, Integer::parseInt)); Assert.assertArrayEquals(new Double[]{1.7, 2.99, 3.8}, MatrixUtils.lineToRow("1.7 2.99 3.8", Double::valueOf)); }
For 2 dims my only success is by “hard coding” the type, see ex:
/** * TODO find a way to use something like E[][] */ public static Double[][] lineToRow(String[] ins) { int i = 0; Double[][] res = new Double[ins.length][3]; for (String ss : ins) { int j = 0; final String[] els = ss.split(" +"); for (String s : els) { res[i][j] = Double.valueOf(s); j++; } i++; } return res; }
It works for 1 dim array because this line (from example 1) is ok:
final E[] res = (E[]) new Object[els.length]; **but not for E[][] ...**