Adding new column at the end of a 2d array

Viewed 113

So I'm trying to add a column at the end of a 2d array. What I've tried to do is to make a copy of the array but with the length being 1 bigger. The only problem is that that expands the rows, not the columns.

// Trying to make the 2d array bigger
public static String[][] FLname = new String[1][0];
FLname = Arrays.copyOf(FLname, FLname.length + 1);

// Inserting the values
FLname[0][FLname.length - 1] = fName;
FLname[1][FLname.length - 1] = lName;

I end up getting a ArrayIndexOutOfBoundsException

Any help would be appreciated!

3 Answers

Stream the outer array and copy inner array

  1. Stream 2D array
  2. map the each element(1D array) to increased column size
  3. collect 1D arrays as 2D array
public static void main(String[] args) {
    final int increaseColumnDelta = 2;
    String[][] input = {null, {"B"}};
    System.out.println(Arrays.deepToString(input));
    String[][] updated = Arrays.stream(input)
            .map(r -> r != null ?
                    Arrays.copyOf(r, r.length + increaseColumnDelta)
                    : new String[increaseColumnDelta])
            .toArray(String[][]::new);
    System.out.println(Arrays.deepToString(updated));
}

Same output array

If the change has to be made in same array,

  1. iterate over the 2D
  2. increase size of each 1D array and copy and assign back
public static void main(String[] args) {
    final int increaseColumnDelta = 2;
    String[][] input = {{"A", "1"}, {"B"}};
    System.out.println(Arrays.deepToString(input));
    IntStream.range(0, input.length)
            .forEach(i -> input[i] = input[i] != null ?
                    Arrays.copyOf(input[i], input[i].length
                            + increaseColumnDelta)
                    : new String[increaseColumnDelta]);
    System.out.println(Arrays.deepToString(input));
}

You can iterate over the rows of this array and replace them with extended ones using Arrays.setAll method as follows:

String[][] arr = {{"one", "two"}, {"three", "four"}, {"five", "six"}};
String[] column = {"two-and-half", "four-and-half", "six-and-half"};
// replace rows of a 2d array
Arrays.setAll(arr, i -> {
    // copy the row of the array and increase its length
    String[] row = Arrays.copyOf(arr[i], arr[i].length + 1);
    // add a new element to the end
    row[row.length - 1] = column[i];
    // return a new row
    return row;
});
// output
Arrays.stream(arr).map(Arrays::toString).forEach(System.out::println);
//[one, two, two-and-half]
//[three, four, four-and-half]
//[five, six, six-and-half]

appending the column by concatenating two streams for each line

public static String[][] flNname = {…};
String[] flNameToAdd = new String[]{‹Your column data here›};
int[] n = {0};
String[][] rslt = Stream.of(flName)
        .map(s -> Stream.concat(Arrays.stream(s), Stream.of(flNameToAdd[n[0]++]))
                .toArray(String[]::new))
        .toArray(String[][]::new);
Related