Home > database >  Converting a Stream<String> to String<Record> is returning void
Converting a Stream<String> to String<Record> is returning void

Time:10-31

I am trying to write a program that will convert a Stream<String> into a String<Record> where everytime there is a comma in the string, it puts that data into one section of the data. My first thought on doing this was to use split() like so:

return fileToStream("data.csv").forEach(s -> s.split(","));

The fileToStream function is simply taking the data.csv and converting it into a Stream I don't quite understand why this is returning void, any help would be greatly appreciated.

I expected it to take something like 123,hello,hello,hello,123,123 and instead of it all being one string, turning it into a record of int, string, string, string, double, double, etc.

CodePudding user response:

forEach doesn't return anything (it is declared as public void forEach(Consumer<? super T> action)). You want to use Stream#map instead:

Returns a stream consisting of the results of applying the given function to the elements of this stream.

However, s.split will return a String array (String[]), not any sort of record. If you want to have instances of a class, you need to construct them, for instance with new Record(s.split(",")) or Record.fromArray(s.split(","))

The Record constructor/factory could then parse the array:

public static Record fromArray(final String[] array) {
  return new Record(
      Integer.parseInt(array[0]),
      array[1],
      array[2],
      array[3],
      Double.parseDouble(array[4]),
      Double.parseDouble(array[5]));
}

But since you are parsing a CSV file, you are better off using a CSV parser such as opencsv.

CodePudding user response:

Assuming fileToStream is returning each record of the CSV as a stream what you wanna do is probably map to a record and then collect the result.

Foreach only loops throgh the Collection like an iterator, it doesn't return anything.

fileToStream("data.csv").forEach(s -> s.split(","));

is equivalent to:

for(String s : fileToStream("data.csv")) {
 s.split(","); // note that you are splitting and ignoring the return result
}

(It actually is a bit different as stream uses the default iterator and the collection iterator will use the forEach method of the collection, but in this use case we can ignore this fact for now, the result in this case is the same)

return fileToStream("data.csv").forEach(s -> s.split(","))
        .map(***your conversion logic***).collect(Collectors.toList()); //or toList() depending on your Java version
  • Related