我正在为 Java 8 中的文件编写解析器。使用 Files.lines
读取该文件并返回一个顺序 Stream<String>
.
每一行映射到一个数据对象Result
像这样:
Result parse(String _line) {
// ... code here
Result _result = new Result().
if (/* line is not needed */) {
return null;
} else {
/* parse line into result */
return _result;
}
}
现在我们可以将流中的每一行映射到相应的结果:
public Stream<Result> parseFile(Path _file) {
Stream<String> _stream = Files.lines(_file);
Stream<Result> _resultStream = _stream.map(this::parse);
}
但是流现在包含 null
我要删除的值:
parseFile(_file).filter(v -> v != null);
我如何结合映射/过滤操作,正如我在 parseLine/_stream.map
中已经知道的那样如果需要结果?
最佳答案
正如评论中已经指出的那样,流将一次性处理,因此实际上不需要更改任何内容。对于它的值(value),你可以使用 flatMap
并让 parse
返回一个流:
Stream<Result> parse(String _line) {
.. code here
Result _result = new Result().
if (/* line is not needed */) {
return Stream.empty();
} else {
/** parse line into result */
return Stream.of(_result);
}
}
public Stream<Result> parseFile(Path _file) {
return Files.lines(_file)
.flatMap(this::parse);
}
这样一来,您将不会有任何 null
值。
关于Java 8 : Applying Stream map and filter in one go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26779676/