YAJSQ - Yet Another Java Streams Question

snotnose

Ars Praefectus
3,454
Subscriptor
Code:
Works in a different program:

    String []data = Files.readAllLines(Paths.get(fileName))
                        .stream().toArray(String[] ::new);

Doesn't work for what I want to do now:

    String input = Files.readString(Paths.get(fileName))
                 .stream().map(line -> line.replaceAll("\t", ""));

First, what does .stream() actually mean? Googling it just gets me the stream docs with no mention of the () thing.

Second, in the latter case I'm trying to read a file in as a single string, converting \n\t into \n in one fell swoop. What am I doing wrong?

Bonus question: Am I falling into the rabbit hole of all input can be treated as a stream, to be manipulated into a form the rest of the program wants to deal with?
 

Apteris

Ars Tribunus Angusticlavius
9,591
Subscriptor
First, what does .stream() actually mean? Googling it just gets me the stream docs with no mention of the () thing.
It seems a Java tutorial is in order. What you're asking about is called a method, and the parentheses enclose the list of parameters this method takes. In this case, there are zero parameters.

Second, in the latter case I'm trying to read a file in as a single string, converting \n\t into \n in one fell swoop. What am I doing wrong?
There are a number of things wrong here; my main recommendation is to do at least one Java tutorial, such as the one linked above.

Then (list not necessarily exhaustive):
1. you're only replacing \t, not \n, in the code snippet you posted.
2. the stream you defined there only contains an intermediate operation, and no terminal operation. This means that nothing will actually happen when you run this code, as streams in Java are lazy.

The JavaDoc":i3h1vevq said:
Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.
3. Lastly, you'd need to convert the resulting stream of strings to a single one. You might find Collectors.joining() relevant to your interests.

Bonus question: Am I falling into the rabbit hole of all input can be treated as a stream, to be manipulated into a form the rest of the program wants to deal with?
On the whole, it seems you're new to programming. This is perfectly ok, but you're kind of in the medium-depth region at the moment. Go to the beginning (e.g. at the start of the tutorial I linked to above) and start from there.
 

Lt_Storm

Ars Tribunus Angusticlavius
21,346
Subscriptor++
The thing which you seem to be missing is an understanding of types. Basically, a type is the set of things that you can do a particular set of actions to. For instance, I can throw a ball, but cannot throw a truck. So, ball.throw() is sensible but truck.throw() is not. Balls and trucks are therefore not of the same type. Any two things which you can do the same actions to are of the same type.

In Java, types boil down to classes and interfaces. An interface is a general type, something like "can be thrown" whereas a class is a specific type "something like Basketball".

So, lets apply this to your code. Files is a class which contains static functions for dealing with files. ReadAllLines is a function which returns a List of Strings (the lines of the file) which, being a List, can be converted to a Stream using the stream method which you can (but should not) turn into an array using toArray. (Lists are generally similar to but preferable to arrays.) So a better bit of code that does what you are doing there would be:

Code:
List<String> data = Files.readAllLines(Paths.get(filename));

readString, on the other hand, reads the entire contents of the file into a single string. As such, it doesn't make sense to try and stream() it. After all, you don't have a list of lines, but instead just one long string. Also, this means that it doesn't make sense to map it. It is, again, just one string. So, let's play around with some code.

Code:
First, let's do what you did to the first one.

String[] data = Files.readString(Paths.get(fileName))
   .split('\n')
   .stream()  // this line is unnecessary, as Lists can also be toArrayed.
   .toArray(String[] ::new);

Again, this would be better as:
List<String> data = Files.readString(Paths.get(fileName)).split('\n');

Now moving on to what you want done:

String input = Files.readString(Paths.get(filename))
   .replaceAll("^\t+" ""); // note the regular expression, 
                           // this matches one or more tabs 
                           // at the beginning of a line.
                           // If you only want to remove 1 tab, 
                           // remove the '+'.

or

List<String> data = Files.readAllLines(Paths.get(filename))
   .stream()
   .map(l -> l.replaceAll("^\t+", ""))
   .collect(Collectors.toList());

And, of course, if getting a single string out matters (I am
not sure that is something you should want)

List<String> data = Files.readAllLines(Paths.get(filename))
   .stream()
   .map(l -> l.replaceAll("^\t+", ""))
   .collect(Collectors.joining('\n'));


Sidenote, I am reminded why I hate Java*. They add a whole bunch of unnecessary bullshit where I have to convert between a List and a Stream because for some reason a List can't be a Stream (the reason is because of Java's type system, but still, I hates it). That would all have required so much less boilerplate in Kotlin.
 

snotnose

Ars Praefectus
3,454
Subscriptor
Haven't had time to digest all the info above, but a few things.

1) I want 1 string because I already have a parser that works with a single string. I realize I could use a stringbuilder, or call my parser several times, but, well....

2) I've got 40 years writing C, mostly embedded systems. Several years ago I learned Java, but haven't used it in 3-4 years. Amazing how fast you can forget stuff.

3) I know () means method, what I don't understand is what putting .stream() in my stream does and I can't find any docs on it.

With streams I'm at the point of understanding where I can get things to work, then suddenly something that seems like it should work does something unexpected and I hit a brick wall trying to figure it out.
 

Apteris

Ars Tribunus Angusticlavius
9,591
Subscriptor
General recommendation: download IntelliJ IDEA and use it for your Java development. When you want to see a method's javadoc or implementation, it will be one key press away.

Colection#stream() JavaDoc

Code:
default Stream<E> stream()

Returns a sequential Stream with this collection as its source.

This method should be overridden when the spliterator() method cannot return a spliterator that is IMMUTABLE, CONCURRENT, or late-binding. (See spliterator() for details.)

Implementation Requirements:
    The default implementation creates a sequential Stream from the collection's Spliterator.
Returns:
    a sequential Stream over the elements in this collection
Since:
    1.8

So, you don't "put .stream() in your stream"; rather, you call .stream() on a Collection (you can do this on some other types as well), and then instead of a collection object you have a stream object, on which you can invoke an arbitrary number of intermediate operations, with a terminal operation at the end.

Again, read the JavaDoc for the java.util.stream package.
 

Lt_Storm

Ars Tribunus Angusticlavius
21,346
Subscriptor++
General recommendation: download IntelliJ IDEA and use it for your Java development. When you want to see a method's javadoc or implementation, it will be one key press away.

+💯 Do this. It makes life so much easier whether you are learning or a professional. Intellij IDEA is a wonderful tool and the community edition is free (but the professional edition is well worth the money). Plus, it works for so many different languages.
 

Lt_Storm

Ars Tribunus Angusticlavius
21,346
Subscriptor++
Haven't had time to digest all the info above, but a few things.

1) I want 1 string because I already have a parser that works with a single string. I realize I could use a stringbuilder, or call my parser several times, but, well....

First, a StringBuilder is the wrong solution for that. Turning such a list into a single string is as simple as String.join("\n", list). So, do that instead if you end up with the list. That said, there is no reason not to use Files.readString() and the regular expression I mentioned. I mostly went through the other ones as both an exercise for myself (It has been a little while since I have used Java myself) and to show you 10 different ways to do the same thing.

2) I've got 40 years writing C, mostly embedded systems. Several years ago I learned Java, but haven't used it in 3-4 years. Amazing how fast you can forget stuff.

3) I know () means method, what I don't understand is what putting .stream() in my stream does and I can't find any docs on it.

This is why I mentioned type theory. .stream() turns your Collection into a Stream which, for some idiotic reason having to do with Collections being mutable and Java's love of boilerplate, a Collection isn't in Java. Of course, unlike in C, a Java String isn't a Collection, or really, trying to be one.

With streams I'm at the point of understanding where I can get things to work, then suddenly something that seems like it should work does something unexpected and I hit a brick wall trying to figure it out.

The problem there is pretty much always the type of the thing being returned. Find the javadoc for whatever method you are using and note the return types. IntelliJ IDEA really is the magic key for that kind of thing. (Even I have to use the Javadocs to be certain what the return type of things like File.readString(), and I have been doing Java development for years. Such cheat sheets are always wonderfully useful.)