【问题标题】:Is there a way to accept values directly into List using BufferedReader? [duplicate]有没有办法使用 BufferedReader 将值直接接受到 List 中? [复制]
【发布时间】:2021-01-30 17:58:14
【问题描述】:
对于我们可以使用的数组:
int[] arr = Arrays.stream(br.readLine().trim.split("\\s+"))
.maptoInt(Integer::parseInt)
.toArray();
有没有类似的方法在 1 步中初始化 List?
【问题讨论】:
标签:
java
list
java-8
java-stream
bufferedreader
【解决方案1】:
使用自动装箱方法并收集到一个列表中,而不是调用toAray()
...
.boxed().collect(Collectors.toList());
注意:您的变量将是一个类似List<Integer> intList = ... 的列表
【解决方案2】:
如果您的文件中有多行仅由空格分隔的整数,您可以阅读
然后全部放入一个列表如下:
List<Integer> list = null;
try {
list = Files.lines(Path.of("c:/someFile.txt"))
.flatMap(line -> Arrays.stream(line.trim().split("\\s+")))
.map(Integer::parseInt)
.collect(Collectors.toList());
} catch (IOException ioe) {
ioe.printStackTrace();
}
要像您的示例那样在一行中读取,您可以这样做。
List<Integer> list = Arrays.stream(br.readLine().trim().split("\\s+"))
.map(Integer::parseInt)
.collect(Collectors.toList());