Home > Software engineering >  Convert two dimensional array of double to string in Java
Convert two dimensional array of double to string in Java

Time:07-14

Is there a simple way to convert double[][] to a String, showing all the values?

Arrays.deepToString does not work, because the inner values are double[], which creates a compilation error:

 incompatible types: double[] cannot be converted to java.lang.Object[]

Arrays.toString will compile, but the resulting string is something like [[D@64c25a62, [D@43e8f1c], which is not very useful.

I think the most concise solution is something like

Arrays.stream(a).
   map(Arrays::toString).
   collect(Collectors.joining("[", "," "]"))

which isn't exactly concise.

Is there something better?

EDIT

Actually, Arrays.deepToString does do what I want. The error I was seeing that I thought mean it didn't work was from trying to pass a double[] to deepToString

CodePudding user response:

Note that Arrays#deepToString should only be used for multi-dimensional arrays when dealing with primitives. The error you got was because you attempted to pass a single-dimensional array of primitives, which should instead be sent to Arrays#toString.

double[] one = new double[]{4};
double[][] two = new double[][]{new double[]{1}, new double[]{2}, new double[]{3}};
String res;
res = Arrays.deepToString(two); //Good: #deepToString takes double[][]
res = Arrays.toString(one); //Good: #toString takes double[]
res = Arrays.deepToString(one); //compilation error: #deepToString cannot use double[]

(Above tested on Java 8 and 17).

Per the javadoc of Arrays#deepToString:

If an element e is an array of a primitive type, it is converted to a string as by invoking the appropriate overloading of Arrays.toString(e). If an element e is an array of a reference type, it is converted to a string as by invoking this method recursively.

CodePudding user response:

you can use this code:

Double[][] test = {{1.0,1.2},{2.0,2.1}};
StringBuilder sb = new StringBuilder();

Stream.of( test ).forEach( array -> sb.append( List.of( array ) ) );

System.out.println( sb );

Output:

[1.0, 1.2][2.0, 2.1]

CodePudding user response:

Use streams...

Double[][] test = {{1.0,1.2},{2.0,2.1}};
String s = Arrays.stream(test)       // Stream<Double[]>
          .flatMap(Arrays::stream)   // Stream<Double>
          .map(Object::toString)     // Stream<String>
          .collect(Collectors.joining(",", "[", "]"));
System.out.println(s);

flatMap will convert inner array to streams and catenate the streams into a single one.

If you want the same with double then convcert to the appropriate stream:

double[][] test2 = {{1.0,1.2},{2.0,2.1}};
System.out.println(test2);
String s = Arrays.stream(test2)            // Stream<double[]>
          .flatMapToDouble(Arrays::stream) // DoubleStream
          .map(Object::toString)           // Stream<String>
          .collect(Collectors.joining(",", "[", "]"));
System.out.println(s);
  • Related