0

As the title, is there any clean Java syntax that supports converting a float array to a string concatenated by comma?

I tried searching for Java stream, but it does not support float array well.

// input: 
float[] input = new float[]{1.0f, 0.95f, 0.11f};

// expected output: 
"1.0,0.95,0.11"

Update: Of course, there are many approaches, I can even use a simple loop to do it. But compared to String.join() for String or Java Stream for double[], I would like to know if there's one for float[].

Steven Chou
  • 1,504
  • 2
  • 21
  • 43
  • 2
    `System.out.println(Arrays.stream(input).mapToObj(d -> String.format("%3.2f", d)).collect(Collectors.joining(", ")));` – Hovercraft Full Of Eels Feb 20 '23 at 03:49
  • 2
    @HovercraftFullOfEels Arrays.stream is not supporting a float array. – Steven Chou Feb 20 '23 at 04:31
  • A simple research can maybe help you : https://stackoverflow.com/questions/37987051/how-to-concatenate-a-string-with-the-new-1-8-stream-api#37987434. You will need to box your float primitive and convert your array to a stream first – Dupeyrat Kevin Feb 20 '23 at 11:31

2 Answers2

1

I think that those two options would be acceptable if you extract the logic to sperate method and name it properly.

    // Option 1
    float[] input = new float[] {1.0f, 0.95f, 0.11f};
    var stringArray = Arrays.toString(input);
    stringArray = stringArray.substring(1, stringArray.length() - 1);
    stringArray = stringArray.replaceAll(" ", "");
    System.out.println(stringArray);
    // Result: 1.0,0.95,0.11

    // Option 2
    var stringBuilder = new StringBuilder();
    for (var value : input) {
      stringBuilder.append(value).append(",");
    }
    stringBuilder.setLength(stringBuilder.length() - 1);
    System.out.println(stringBuilder);
    // Result: 1.0,0.95,0.11
1

I figured out a close answer:

float[] input = new float[]{1.0f, 0.95f, 0.11f};

// output: 1.0,0.95,0.11
System.out.println(
        IntStream.range(0, input.length)
                .mapToObj(i -> String.valueOf(input[i]))
                .collect(Collectors.joining(","))
);

The idea is to use the IntStream to create an array index first, then map to each array element.

Steven Chou
  • 1,504
  • 2
  • 21
  • 43