1

I have a file where each line is a pipe-delimitted string of float values. I am reading the file line by line and splitting by "|" and then casting each element to a float. I can use Java streams to get this as a Float array, but I want to know if it is possible to get this as the primitive float[] array. The reason being is that I am passing these values into a library which expects float[].

Here is my code:

br = Files.newBufferedReader(Paths.get(inputFile));
String[] lines = br.lines().toArray(String[]::new);

for(String line : lines) {
    Float[] inputs = 
             Arrays.stream(line.split("|"))
                   .map((x) -> Float.parseFloat(x))
                   .toArray(Float[]::new);
}

Is there a way to use streams to get a primitive float[] array, or do I still need to iterate over the Float[] and convert? I looked into DoubleStream, but I can't have a double[].

Thanks

EDIT: thanks for all comments. Ended up iterating over Float[] and calling .floatValue on each element and storing the value in a float[].

Seephor
  • 1,692
  • 3
  • 28
  • 50
  • 1
    And not with `Float`. You can `mapToDouble` and then `toArray`. – Sotirios Delimanolis Dec 14 '16 at 19:06
  • @SotiriosDelimanolis forgot to escape it when typing here. it is escaped in my code. – Seephor Dec 14 '16 at 19:06
  • @SotiriosDelimanolis mapToDouble still gives me a double array, unless there is a way to get it to give me a float[]. if so, please show. – Seephor Dec 14 '16 at 19:06
  • @JimGarrison won't that give me a double[]? I need float[]. I could then just do toArray(float[])? – Seephor Dec 14 '16 at 19:07
  • 4
    "[..] not with `Float`" You'll have to do it yourself. – Sotirios Delimanolis Dec 14 '16 at 19:07
  • @JimGarrison I am not able to use primitive float[] in List.toArray. Do you have an example of that? I tried: Float[] inputs = Arrays.stream(line.split("\\|")).map((x) -> Float.parseFloat(x)).collect(Collectors.toList()).toArray(float[]); – Seephor Dec 14 '16 at 19:15
  • 2
    @Seephor there's _not_ going to be a good way of doing this other than by hand. No built in utility will help. – Louis Wasserman Dec 14 '16 at 19:21
  • 1
    [Here](http://stackoverflow.com/a/26970398/2711488) is a Stream based solution for collecting a `DoubleStream` into a `float[]` array. All you have to change in your code to use it, is to replace `.map((x) -> Float.parseFloat(x))` with `.mapToDouble(Float::parseFloat)` to create a `DoubleStream` (so the `float` gets temporarily promoted to `double`, but it should stay in the defined value set). – Holger Dec 14 '16 at 19:39

0 Answers0