小编典典
没有任何额外的帮助程序功能或外部库,最简单的方法是:
Stream lines1 = Files.lines(Paths.get("/somepathtofile"));
Stream lines2 = Files.lines(Paths.get("/somepathtoanotherfile"));
Stream.concat(lines1, lines)
.filter(...)
.forEach(...);
如果Files.lines尚未声明抛出受检查的异常,则可以
Stream.of("/file1", "/file2")
.map(Paths::get)
.flatMap(Files::lines)....
但是,a,我们不能这样做。有几种解决方法。一种是制作自己的版本,将Files.lines其称为标准版本,然后将其IOException作为捕获并重新抛出UncheckedIOException。另一种方法是使用抛出检查异常的方法来制造函数的更通用的方法。它看起来像这样:
@FunctionalInterface
public interface ThrowingFunction extends Function {
@Override
public default R apply(T t) {
try {
return throwingApply(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Function wrap(ThrowingFunction f) {
return f;
}
R throwingApply(T t) throws Exception;
}
然后
Stream.of("/somefile", "/someotherfile", "/yetanotherfile")
.map(Paths::get)
.flatMap(ThrowingFunction.wrap(Files::lines))
.....
那里有几个库需要为每个功能接口编写类似上面的内容的麻烦。
2020-11-16