Java 8 stream emitting a stream

前端 未结 2 1331
无人共我
无人共我 2020-12-03 19:41

I have the following file format:

Text1
+ continuation of Text1
+ more continuation of Text1 
Text2
+ continuation of Text2
+ more continuation of Text2
+ ev         


        
2条回答
  •  情书的邮戳
    2020-12-03 20:23

    In Java 9, you could use

    static final Pattern LINE_WITH_CONTINUATION = Pattern.compile("(\\V|\\R\\+)+");
    

    try(Scanner s = new Scanner(file)) {
        s.findAll(LINE_WITH_CONTINUATION)
            .map(m -> m.group().replaceAll("\\R\\+", ""))
            .forEach(System.out::println);
    }
    


    Since Java 8 lacks the Scanner.findAll(Pattern) method, you may add a custom implementation of the operation as a work-around

    public static Stream findAll(Scanner s, Pattern pattern) {
        return StreamSupport.stream(new Spliterators.AbstractSpliterator(
                1000, Spliterator.ORDERED|Spliterator.NONNULL) {
            public boolean tryAdvance(Consumer action) {
                if(s.findWithinHorizon(pattern, 0)!=null) {
                    action.accept(s.match());
                    return true;
                }
                else return false;
            }
        }, false);
    }
    

    which can be used like

    try(Scanner s = new Scanner(file)) {
        findAll(s, LINE_WITH_CONTINUATION)
            .map(m -> m.group().replaceAll("\\R\\+", ""))
            .forEach(System.out::println);
    }
    

    which will make the future migration easy.

提交回复
热议问题