简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM