【问题标题】:turn string separated by spaces to arraylist of integers in one line将由空格分隔的字符串转换为一行中的整数数组列表
【发布时间】:2018-07-21 04:04:59
【问题描述】:

假设我有字符串"5 12 4"。我想把它变成一个 ArrayList 的整数,在单个功能行中包含 5,12 和 4。

我觉得应该有办法做到这一点,将split(" ") 组合成stream,使用mapToInt(s->Integers.parseInt(s))collect(Collectors.toList())。类似的东西:

ArrayList<Integer> nextLine = Arrays.stream(inputLine.split(" "))
.mapToInt(s->Integer.parseInt(s))
.collect(Collectors.toList());

但这不起作用,因为mapToInt 给我ints 而不是Integers。

我知道如何使用循环来做到这一点。如果存在,我想要一种在单个流操作中执行此操作的方法。

【问题讨论】:

    标签: java string arraylist int java-stream


    【解决方案1】:

    您可以使用Integer#valueOf。请注意,您应该使用 Stream#map 而不是 Steam#mapToInt

    List<Integer> nextLine = 
        Arrays.stream(inputLine.split(" "))
              .map(Integer::valueOf)
              .collect(Collectors.toList());
    

    【讨论】:

    • 是的,这行得通,谢谢。只要允许,我就会接受。
    【解决方案2】:

    mapToInt 返回一个IntStream,并且您不能将原始元素累积到ArrayList&lt;T&gt;,因此您可以利用map 操作将产生Stream&lt;Integer&gt;,然后您可以将元素累积到ArrayList&lt;T&gt; .

    也就是说,即使您将 .mapToInt(s -&gt; Integer.parseInt(s)) 更改为
    .map(s -&gt; Integer.parseInt(s)),您的代码仍然无法编译,因为结果的接收器类型是 ArrayList&lt;Integer&gt; 类型,而 collect 终端操作将返回 @在这种特定情况下为 987654331@。

    因此,要解决剩下的问题,您可以将接收器类型设置为 List&lt;Integer&gt;,或者保留接收器类型,然后执行 .collect(Collectors.toCollection(ArrayList::new)); 进行归约操作,从而产生特定的 List 实现。

    已发布答案的另一个变体是:

    ArrayList<Integer> resultSet =
           Pattern.compile(" ")
                  .splitAsStream(inputLine)
                  .map(Integer::valueOf)
                  .collect(Collectors.toCollection(ArrayList::new));
    

    【讨论】:

    • 该变体的优点是它不会创建一个您无论如何都不会使用的中间数组。 +1
    • @FedericoPeraltaSchaffner 对,你也可以使用\\s
    • @Eugene String.split 也支持"\\s"
    猜你喜欢
    • 2018-02-16
    • 2021-03-13
    • 2021-01-22
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    相关资源
    最近更新 更多