Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading