williamstome
williamstome

Reputation: 776

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?

Upvotes: 3

Views: 222

Answers (2)

apnorton
apnorton

Reputation: 2440

A one-line approach:

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

Upvotes: 9

rolfl
rolfl

Reputation: 17707

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));

Upvotes: 2

Related Questions