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?