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[].

8
  • 1
    And not with Float. You can mapToDouble and then toArray. Commented Dec 14, 2016 at 19:06
  • @SotiriosDelimanolis forgot to escape it when typing here. it is escaped in my code. Commented Dec 14, 2016 at 19:06
  • 4
    "[..] not with Float" You'll have to do it yourself. Commented Dec 14, 2016 at 19:07
  • 2
    @Seephor there's not going to be a good way of doing this other than by hand. No built in utility will help. Commented Dec 14, 2016 at 19:21
  • 1
    Here 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). Commented Dec 14, 2016 at 19:39

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.