-5

I'm fairly new to using streams, and I wanted to try parsing a config file with them.

I have a file setup like so...

[Category 1]
1 2 3 4
5 6 7 8

[Category 2]
9 8 7 6
5 4 3 2

How would I go about getting all the lines from one of these categories using Streams? Is there a clean way to do it using Streams?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Taztingo
  • 1,915
  • 2
  • 27
  • 42
  • 2
    Seems like it would be simpler to just use a loop for this – GBlodgett May 17 '19 at 13:26
  • I agree, but I wanted to see if there was a way to do it with Streams. I'm not sure why there are so many down votes on the question. Doesn't seem like it would be hard to say "Yes" with an example or just "No". – Taztingo May 17 '19 at 13:27
  • 3
    The downvotes are caused by lack of evidence of your research or attempt to solve the problem. – Fureeish May 17 '19 at 13:30
  • 1
    imho, Streams should be avoided when the order matters. Streams are handy when you need to filter/map/collect a Collection where sequence does not matter. Reading a file often must be done line by line, sequentially. Also, line number is often useful. For those reasons, Stream seems a bad idea in this use case. – Arnaud Denoyelle May 17 '19 at 13:35

1 Answers1

2

You could combine dropWhile and takeWhile methods introduced in Java 9. If you are searching for lets say [Category 2] drop all lines before it, and continue processing all lines until you find empty line (or until stream will end but that case is covered automatically).

Demo (for more info about split("\\R") see https://stackoverflow.com/a/31060125):

String data =
        "[Category 1]\n" +
        "1 2 3 4\n" +
        "5 6 7 8\n" +
        "\n" +
        "[Category 2]\n" +
        "9 8 7 6\n" +
        "5 4 3 2\n" +
        "\n" +
        "[Category 3]\n" +
        "1 3 7 6\n" +
        "4 4 3 2\n";

Stream.of(data.split("\\R"))  // form Java 8 regex engine supports \R as line separator
      .dropWhile(line->!line.equals("[Category 2]"))
      .takeWhile(Predicate.not(String::isEmpty))
      .forEach(System.out::println);

Output:

[Category 2]
9 8 7 6
5 4 3 2
Pshemo
  • 122,468
  • 25
  • 185
  • 269