代码之家  ›  专栏  ›  技术社区  ›  MWB

如何拆分字符串流并生成字符串数组列表?

  •  9
  • MWB  · 技术社区  · 7 年前

    我对小溪还比较陌生,所以请帮帮我(温柔点)。

    我想做的是如下。我有一个 BufferedReader 它从一个文件中读取,其中每一行看起来像这样:“A,B”。例如:

    示例输入文件

    “A,B”

    “D,E”

    “F,G”

    我想把这个换成 LinkedList<String[]> :

    例子 LinkedList<字符串[]gt;

    [“A”、“B”、“C”、“D”、“F”、“G”]

    您将如何使用流方法实现这一点?

    这就是我所尝试的:

    List numbers = reader.lines().map(s -> s.split("[\\W]")).collect(Collectors.toList());
    

    这不起作用。我的IDE提供以下反馈:

    Incompatible types. Required List but 'collect' was inferred to R: no instance(s) of type variable(s) T exist so that List<T> conforms to List
    

    它表明…我仍在努力想办法解决问题。

    3 回复  |  直到 7 年前
        1
  •  6
  •   Ousmane D.    7 年前

    首先,我建议避免使用原始类型,而是使用 List<String[]> 作为接收器类型。

    List<String[]> numbers = reader.lines()
                                   .map(s -> s.split(delimiter)) // substitute with your deilimeter
                                   .collect(Collectors.toList());
    

    你提到你想要一个 LinkedList 实施。你几乎应该总是喜欢 ArrayList 哪一个 toList 默认返回 目前 尽管不能保证持久性,但是可以使用 toCollection :

    List<String[]> numbers = reader.lines()
                                   .map(s -> s.split(delimiter)) // substitute with your deilimeter
                                   .collect(Collectors.toCollection(ArrayList::new));
    

    同样地 链表 :

    List<String[]> numbers = reader.lines()
                                   .map(s -> s.split(delimiter)) // substitute with your deilimeter
                                   .collect(Collectors.toCollection(LinkedList::new));
    
        2
  •  4
  •   Ravindra Ranwala    7 年前

    你可以这样做,

    Path path = Paths.get("src/main/resources", "data.txt");
    try (Stream<String> lines = Files.lines(path)) {
        List<String> strings = lines.flatMap(l -> Arrays.stream(l.split(","))).map(String::trim)
            .collect(Collectors.toCollection(LinkedList::new));
    }
    

    读取文件的每一行,然后使用分隔符将其拆分。之后,修剪它以消除任何剩余的空白字符。最后将其收集到结果容器中。

        3
  •  4
  •   Ousmane D.    7 年前

    假设每行都是2个元素的元组,您可以将它们收集到一个类似于2个元素的元组的列表中。 请注意,Java没有用于元组的本地类型(如斯卡拉或Python),因此您应该选择一种表示元素的方式。

    您可以创建条目列表:

    List<Map.Entry<String, String>> numbers = 
                     reader.lines()
                           .map(s -> s.split(","))
                           .map(a -> new AbstractMap.SimpleEntry<>(a[0], a[1]))
                           .collect(Collectors.toList());
    

    或字符串列表:

    List<String> numbers = reader.lines()
                                 .map(s -> s.split(","))
                                 .map(a -> "{" + a[0] + "," + a[1] + "}"))
                                 .collect(Collectors.toList());
    

    请注意,一般情况下,在收集流时,您不希望坚持使用特定的列表实现,而在某些情况下,您可能需要这样做。在这种情况下,请指定要与之一起使用的收集供应商 toCollection(LinkedList::new) 而不是 toList()