How to avoid the last new line in when writing to a File using the Stream API and Printwriter?

3579 views java
10

I am studying the Lambdas and Stream API that comes with Java 8. I wanted to create a file something like this using Stream API just for exercising purposes:

b
bb
bbb
bbbb
bbbbb
bbbb
bbb
bb
b

and this is the implementation I came up with:

final File file = new File("/Users/kt/sample.data");
final PrintWriter printWriter = new PrintWriter(file);

Stream.concat(IntStream.iterate(1, i -> i + 1).limit(6).boxed(), 
              IntStream.iterate(5, i -> i - 1).limit(5).boxed())
      .map(counter -> {
          StringBuilder stringBuilder = new StringBuilder();
          IntStream.range(1, counter).forEach(c -> stringBuilder.append("b"));
          return stringBuilder.toString();
      }).filter(s -> s.length() != 0).forEach(s -> printWriter.println(s));

printWriter.flush();
printWriter.close();

Now the only problem is, I end up with an empty last line in the file, since printwriter is printing the last 'b' together with a new line.

Obviously I can pass 4 instead of 5 to 2nd IntStream.iterate I have and before flushing the printWriter I can do: printWriter.print("b");, but my goal is to harness the Stream API.

How can I achieve this more Streamy?

answered question

1 Answer

2

You can join your elements with a return line, and then print, and as a tip you can simplify your use of StringBuilder with a map operation :

String str = 
  Stream.concat(
             IntStream.iterate(1, i -> i + 1).limit(6).boxed(),
             IntStream.iterate(5, i -> i - 1).limit(5).boxed())
        .map(counter -> IntStream.range(1, counter).mapToObj(c -> "b").collect(Collectors.joining()))
        .filter(s -> s.length() != 0)
        .collect(Collectors.joining("\n"));

printWriter.print(str);

posted this

Have an answer?

JD

Please login first before posting an answer.