【问题标题】:Reading values from a file and splitting them into two lists with stream in Java从文件中读取值并将它们拆分为两个带有 Java 流的列表
【发布时间】:2020-03-28 00:15:41
【问题描述】:

假设我们有一个带有像这样的给定输入的文件

List1,List2,List3,List4,List5,List6,List7.......
.....List8,List9
ListX1,ListX2,ListX3.......

List9 输入后,多了一个换行符。我如何能够告诉流将换行符之前的元素收集到一个列表中,并将其余的收集到第二个列表中?

List<String> fWire = new ArrayList<String>();
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
        .......
    } catch (IOException e) {
        e.printStackTrace();
    }

【问题讨论】:

  • 你是说每一行输入都要解析成一个单独的List?
  • 只有两行,所以从技术上讲,是的,每个输入行都应该被解析成一个单独的列表。
  • 对我来说,如果过度使用流来完成此类任务。只需按照标准方式进行即可。
  • 如果存在两个列表遵循的模式,您可以使用过滤器功能并将其相应地转储到相应的列表中

标签: java file arraylist split java-stream


【解决方案1】:

您似乎需要List&lt;List&lt;String&gt;&gt;。每个内部List 将代表一行输入:

List<List<String>> lists = null;
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
    lists = stream.map(s -> Arrays.asList(s.split(",")))
                  .collect(Collectors.toList());
} catch (IOException e) {
    e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 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
    相关资源
    最近更新 更多