Daiquiri Daiquiri - 1 year ago 109
Java Question

Accumulate a Java Stream and only then process it

I had a document that looked like the following:


100, "some text"
101, "more text"
102, "even more text"

I processed it using regex and returned a new processed documents as the follow:

Stream<String> lines = Files.lines(Paths.get(data.txt);
Pattern regex = Pattern.compile("([\\d{1,3}]),(.*)");

List<MyClass> result =
.map(m -> new MyClass(m.group(1), m.group(2)) //MyClass(int id, String text)

This returns a list of MyClass processed. Can run in parallel and everything is ok.

The problem is that I now have this:


101, "some text
the text continues in the next line
and maybe in the next"
102, "for a random
of lines"
103, "until the new pattern of new id comma appears"

So, I somehow need to join lines that are being read from the stream until a new match appear. (Something like an buffer?)

I tried to Collect strings and then collect MyClass(), but with no success, because I cannot actually split streams.

Reduce comes to mind to concatenate lines, but I'll concatenate just lines and I cannot reduce and generate a new stream of lines.

Any ideas how to solve this with java 8 streams?

Answer Source

This is a job for java.util.Scanner. With the upcoming Java 9, you would write:

List<MyClass> result;
try(Scanner s=new Scanner(Paths.get("data.txt"))) {
    result = s.findAll("(\\d{1,3}),\\s*\"([^\"]*)\"")
                //MyClass(int id, String text)
    .map(m -> new MyClass(Integer.parseInt(m.group(1)), m.group(2))) 

but since the Stream producing findAll does not exist under Java 8, we’ll need a helper method:

private static Stream<MatchResult> matches(Scanner s, String pattern) {
    Pattern compiled=Pattern.compile(pattern);
    return StreamSupport.stream(
        new Spliterators.AbstractSpliterator<MatchResult>(1000,
                         Spliterator.ORDERED|Spliterator.NONNULL) {
        public boolean tryAdvance(Consumer<? super MatchResult> action) {
            if(s.findWithinHorizon(compiled, 0)==null) return false;
            return true;
    }, false);

Replacing findAll with this helper method, we get

List<MyClass> result;
try(Scanner s=new Scanner(Paths.get("data.txt"))) {

    result = matches(s, "(\\d{1,3}),\\s*\"([^\"]*)\"")
               // MyClass(int id, String text)
    .map(m -> new MyClass(Integer.parseInt(m.group(1)), m.group(2)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download