I'm writing a parser for a programming language, and I was thinking Java's takeWhile method might be perfect for grouping the lexical tokens into structures. As an example case, to get a stream of tokens representing a brace-delimited code block, I could write:
stream.dropWhile(t -> !t.equals("{")).takeWhile(t -> !t.equals("}")))
…Except, obviously that wouldn't work if the block in question had nested blocks, such as a function declaration. In a more imperative style, I might do this after the opening brace:
assert(openCurlyToken.equals("{");
List blockTokens = new ArrayList<String>();
blockTokens.add(openCurlyToken);
String token;
int braceLevel = 1;
while (braceLevel > 0) {
token = nextToken();
if (token.equals("{")) braceLevel++;
else if (token.equals("}")) braceLevel--;
blockTokens.add(t);
}
return blockTokens;
Kinda ugly, kinda verbose. What I'm hoping is there is a more concise way to do this kind of computation using Streams?