The correct answer following the book is:
F. If it prints anything, it will not include commas.
and the explanation says that "The result is printed with one entry on a single line, but all original line breaks and commas from the file are removed"
I spent a lot of hours on internet trying to get a little bit more deep explanation about this piece of code, but I didn´t see anything
I don´t know why is not keeping the original line breaks and commas, why are removed? and why is printed in a single line if the code split the file into lines....
I don´t understand I have been searching on google any answer and I am not able to finde the explanation to this...
I checked Files.lines method as well as flatMap and map methods, but I don´t get the answer.
Please, anybody could help me?
Thank you very much in advance
Thank you for giving good details about where the code comes from Please use the code button, and use spaces for indentation, not tabs, and align the dot operators vertically, then your code will look really nice, like this:-I think line 4 could be changed to .map(String::toUpperCase) See ths part of the Java™ Tutorials.
Now, let's look at all the lines in order.
1: This line creates a Path object representing the squid feeding file.
2: As you already know, Files#lines() produces a Stream<String> where each element starts at the beginning of the line and ends just before the line end sequence (\n, \r\n, etc.) It removes the line separators. So you are not going to get \n or \r or similar in any of your outputs.
3: Left until later: see below.
4: This takes each text entry as received from the previous method and turns it to UPPER CASE.
5: this prints whatever has been sent to it, one line per entry. That means that every time the text is split by a line end or a comma it prints a new piece of text.
There are two parts to line 3. The first is String#split(). This takes a String and divides it into a String divided by its regular expression, here “,”. You start with the individual lines from the file, as from line 2, That splits the String “around” the matches, so the commas are not included in the elements of the array.
What flatMap() does is to take a Stream of arrays or a Stream of Streams and turn it into a Stream of the individual elements. If you have four commas per line, you will get a String with five elements. But the map() method would turn that into one element, being the whole array. The flatMap() method changes that to a five‑element included in a Stream containing the individual pieces of text.
posted 2 weeks ago
It has been super useful your explanations, I just realised that I didn´t know how the String split(String s) method worked. So I know now why the "," (commas) are not in the output.
And I have much more clear how Files.lines method works!
Thank you so much for your wide and accurate answer!