How to intercept a Java Stream by a particular data?

I want to use Java to read a .txt file and use Java Stream to handle all the data before the Line "—".

I have used :

return Files.lines(Path.of(path), StandardCharsets.UTF_8)
        .filter(n -> ...)

but I have no clue how to manage the lines or get access to other lines besides n(lambda parameter).

>Solution :

handle all the data before the Line "—"

To implement this condition you can use Java 9 Stream.takeWhile(). It expects a Predicate as an argument. The stream processing would terminate after the first element for which the given predicate would be evaluated to false.

return Files.lines(Path.of(path))
    .takeWhile(line -> !"---".equals(line))
    // other logic
    // terminal operation producing the result, like .toList(), collect(Collectors.joining()), etc.

I suggest you to get familiar with these basic tutorials on Lambda expressions and Streams.

Sidenote: UTF_8 is the default character set, and there’s no need to provide the second argument in Files.lines() if it’s used in the target file.

Leave a Reply