【问题标题】:Populate int[ ] array from console on 1 line with Lambda (java)使用 Lambda (java) 从控制台的 1 行填充 int[] 数组
【发布时间】:2017-05-18 16:09:59
【问题描述】:
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
     Object[] test = Arrays.stream(br.readLine().split(" ")).map(string -> Integer.parseInt(string)).toArray();
     System.out.println(Arrays.toString(test));
} catch (IOException E) {

}

所以这段代码可以工作,但它返回一个 Object[] 类型的数组 但是,我想要的是让它返回一个int[] 类型的数组。

有没有人知道我可以如何做到这一点?

【问题讨论】:

  • 所以你想返回int的数组而不是Object的数组?
  • 是的,我希望它返回一个 int[] 而不是 Object[]

标签: java arrays lambda java-8


【解决方案1】:

要检索int 类型而不是Object 的数组,您可以使用mapToInt 方法。

int[] test = Arrays.stream(br.readLine().split(" "))
                   .mapToInt(Integer::parseInt).toArray();

请注意,您可以通过在 mapToInt 方法的参数中使用 method reference 来简化代码。

阅读:

【讨论】:

  • @ВсеЕдно 您可以使用.collect(Collectors.toCollection(ArrayList::new)); 将流转换为ArrayList,但因为ArrayList 的类型为List,您可以简单地使用.collect(Collectors.toList());,它将流转换为列表.但是,您有什么理由不想使用.collect(Collectors.toList());?有关How to get ArrayList from Stream in Java 8 的更多信息。
  • 如果您想检索 List<T> 而不是数组,请使用:List<Integer> test = Arrays.stream(br.readLine().split(" ")) .mapToInt(Integer::parseInt).boxed().collect(Collectors.toList());
  • 我建议你使用我上次评论的方法,但如果你真的想要ArrayList,那么使用这个:ArrayList<Integer> test = Arrays.stream(br.readLine().split(" ")) .mapToInt(Integer::parseInt).boxed().collect(Collectors.toCollection(ArrayList::new));
  • @Aominè 无需转换为int,然后再转换为Integer。只需使用:ArrayList<Integer> ints = Stream.of(br.readLine().split(" ")).map(Integer::valueOf).collect(Collectors.toCollection(ArrayList::new));
  • @Flown true ,这绝对是一个更简洁的解决方案!我真的很欣赏这个建议,下次会记住这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-03
  • 2018-03-08
相关资源
最近更新 更多