Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenation of multidimensional string arrays in java

I wish to print the contents of String[][] myArray using only one print statement.

Obviously the array can be printed easily by looping through it, but for the sake of clean log files, I'd like the array cleanly printed out using only one println/logging line, and thus need some way of concatenating the array's contents into one big honker string with appropriately placed newlines.

One could always write a one-line scala function to do this no sweat, but I'd prefer to keep this java only.

Is there a straightforward way to do this?

like image 485
williamstome Avatar asked Dec 07 '25 10:12

williamstome


2 Answers

A one-line approach:

System.out.println(java.util.Arrays.deepToString(myArray));

like image 65
apnorton Avatar answered Dec 10 '25 00:12

apnorton


Go with anorton's method.....

=============================

Sure, create a method:

private static final String concatenate(String[][] data) {
    StringBuilder sb = new StringBuilder();
    for (String[] line : data) {
        sb.append(Arrays.toString(line)).append(\n");
    }
    return sb.toString();
}

Then, you can log:

logger.log(concatenate(data));
like image 32
rolfl Avatar answered Dec 10 '25 00:12

rolfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!