[英]Collect list of list using Java 8 Stream API
I have the following line stream that I read from a file 我从文件中读取了以下行流
1 2 4.5 1 2 4.5
1 6 3 5.5 5.3 6 1 6 3 5.5 5.3 6
1 7.2 5 7 1 7.2 5 7
How can I collect these lines in a single list of list considering only the Integers? 如何仅考虑整数就将这些行收集在一个列表中? (Notice that within each line the numbers are separated by one or more white spaces)
(请注意,每一行中的数字都用一个或多个空格隔开)
This is what I tried, but this give me one single list of all integer elements. 这是我尝试过的方法,但这给了我所有整数元素的一个列表。
list = reader.lines()
.map(m -> m.split("\\n"))
.flatMap(Arrays::stream)
.map(m -> m.split("\\s+"))
.flatMap(Arrays::stream)
.filter(f -> !f.contains("."))
.map(Integer::parseInt)
.collect(Collectors.toList());
reader.lines()
.map(line -> Arrays.stream(line.split("\\s+"))
.filter(f -> !f.contains("."))
.map(Integer::parseInt)
.collect(Collectors.toList())
.collect(Collectors.toList())
This should do the trick. 这应该可以解决问题。
list = reader.lines()
.map(line -> Arrays.stream(line.split("\\s+"))
.filter(number -> !number.contains("."))
.map(Integer::parseInt)
.collect(Collectors.toList()))
.collect(Collectors.toList());
You may also want to filter for empty lines: 您可能还需要过滤空行:
list = reader.lines()
.map(line -> Arrays.stream(line.split("\\s+"))
.filter(number -> !number.contains("."))
.map(Integer::parseInt)
.collect(Collectors.toList()))
.map(l -> !l.isEmpty())
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.