【问题标题】:Accumulate a Java Stream and only then process it积累一个Java Stream,然后再处理它
【发布时间】:2016-10-27 23:28:56
【问题描述】:

我的文档如下所示:

数据.txt

100, "some text"
101, "more text"
102, "even more text"

我使用正则表达式处理它并返回一个新的处理文档,如下所示:

Stream<String> lines = Files.lines(Paths.get(data.txt);
Pattern regex = Pattern.compile("([\\d{1,3}]),(.*)");

List<MyClass> result = 
  lines.map(regex::matcher)
       .filter(Matcher::find)
       .map(m -> new MyClass(m.group(1), m.group(2)) //MyClass(int id, String text)
       .collect(Collectors.toList());

这将返回已处理的 MyClass 列表。可以并行运行,一切正常。

问题是我现在有这个:

data2.txt

101, "some text
the text continues in the next line
and maybe in the next"
102, "for a random
number
of lines"
103, "until the new pattern of new id comma appears"

所以,我不知何故需要加入从流中读取的行,直到出现新的匹配项。 (类似于缓冲区的东西?)

我尝试收集字符串,然后收集 MyClass(),但没有成功,因为我实际上无法拆分流。

Reduce 想到连接行,但我只会连接行,我不能减少和生成新的行流。

任何想法如何用 java 8 流解决这个问题?

【问题讨论】:

  • 在我看来,您的输入需要某种原始解析器,您不仅可以处理换行符,还可以处理引号的转义。
  • 您的正则表达式中只有 1 个组。另外,您如何知道下一行是新 ID 还是前一个字符串的一部分?他们都有报价吗?如果字符串包含引号怎么办?您可能需要为此使用 CSV 解析器。
  • 字符串可能包含引号,例如:101、“一些”文本和更多“文本”102、“这是下一个文档”我需要以某种方式缓冲操作系统使用 lambdas 累积行吗?跨度>
  • 看起来您的输入可能是 CSV 文件。您是否考虑过使用 CSV 解析器?
  • 感谢您的建议。我会尝试使用commons.apache.org/proper/commons-csv/apidocs/org/apache/…

标签: java java-8 java-stream reduce collectors


【解决方案1】:

这是java.util.Scanner 的工作。对于即将推出的 Java 9,您可以编写:

List<MyClass> result;
try(Scanner s=new Scanner(Paths.get("data.txt"))) {
    result = s.findAll("(\\d{1,3}),\\s*\"([^\"]*)\"")
                //MyClass(int id, String text)
    .map(m -> new MyClass(Integer.parseInt(m.group(1)), m.group(2))) 
    .collect(Collectors.toList());
}
result.forEach(System.out::println);

但由于在 Java 8 下不存在产生 findAllStream,因此我们需要一个辅助方法:

private static Stream<MatchResult> matches(Scanner s, String pattern) {
    Pattern compiled=Pattern.compile(pattern);
    return StreamSupport.stream(
        new Spliterators.AbstractSpliterator<MatchResult>(1000,
                         Spliterator.ORDERED|Spliterator.NONNULL) {
        @Override
        public boolean tryAdvance(Consumer<? super MatchResult> action) {
            if(s.findWithinHorizon(compiled, 0)==null) return false;
            action.accept(s.match());
            return true;
        }
    }, false);
}

用这个辅助方法替换findAll,我们得到

List<MyClass> result;
try(Scanner s=new Scanner(Paths.get("data.txt"))) {

    result = matches(s, "(\\d{1,3}),\\s*\"([^\"]*)\"")
               // MyClass(int id, String text)
    .map(m -> new MyClass(Integer.parseInt(m.group(1)), m.group(2)))
    .collect(Collectors.toList());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多